在动作之外执行异步操作asp.net mvc

时间:2012-10-18 00:45:14

标签: asp.net asp.net-mvc asynchronous ravendb

我希望能够在每个请求上从云数据库加载用户,并在使用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;
  }
}

那么有没有其他方法可以做到这一点?我注意到基础控制器中有一个begin execute方法:

protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
{
  return base.BeginExecute(requestContext, callback, state);
}

我可以在那里做吗?

1 个答案:

答案 0 :(得分:10)

问题是三个月大,所以我猜你已经设法解决了这个问题。无论如何,我在这里添加我的解决方案,因为我必须做类似的事情。

我使用了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);
    }
}