我希望能够从每个请求云数据库加载用户,并具有可在使用asp.net的MVC控制器的请求。 问题是,目前的框架不支持从操作筛选做异步操作。 所以OnActionExecuting,OnAuthorization方法不允许我这样做。例如,我有以下的代码不工作(所以不要尝试)..你得到一个异常:“异步模块或处理程序,同时异步完成操作仍然悬而未决“。
protected async override void OnAuthorization(AuthorizationContext filterContext)
{
var user = filterContext.HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
HandleUnauthorizedRequest(filterContext);
return;
}
using (var session = MvcApplication.DocumentStore.OpenAsyncSession())
{
User currentUser = await session.LoadAsync<User>(user.Identity.Name);
if (currentUser == null)
{
HandleUnauthorizedRequest(filterContext);
return;
}
filterContext.HttpContext.Items["User"] = currentUser;
}
}
那么,有没有是能够做到这一点任何其他方式? 我注意到有在基座控制器一个开始执行方法:
protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
{
return base.BeginExecute(requestContext, callback, state);
}
我能做到这一点有可能?
现在的问题是三个月大的,所以我想你已经设法解决这个问题。 无论如何,我会在这里我的解决方案,因为我必须做同样的事情。
我曾经从一些方法ParallelExtensionsExtras库。 这是我的课:
public class AsyncControllerBase : Controller
{
protected override IAsyncResult BeginExecute(System.Web.Routing.RequestContext requestContext, AsyncCallback callback, object state)
{
return ExecuteCoreAsync(requestContext, state).ToAsync(callback, state);
}
protected override void EndExecute(IAsyncResult asyncResult)
{
IAsyncResult baseAsyncResult = ((Task<IAsyncResult>)asyncResult).Result;
base.EndExecute(baseAsyncResult);
}
protected virtual async Task<IAsyncResult> ExecuteCoreAsync(System.Web.Routing.RequestContext requestContext, object state)
{
await DoStuffHereOrInDerivedClassAsync();
var baseBeginExecuteCompletion = new TaskCompletionSource<IAsyncResult>();
AsyncCallback callback = ar =>
{
baseBeginExecuteCompletion.SetResult(ar);
};
// OnActionExecuting will be called at this point
var baseAsyncResult = base.BeginExecute(requestContext, callback, state);
await baseBeginExecuteCompletion.Task;
return baseAsyncResult;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}