5

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

我可以在那里做吗?

4

1 回答 1

10

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

我使用了ParallelExtensionsExtras库中的ToAsync方法。这是我的课:

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);
    }
}

另请参阅Microsoft 提供的有关在 Task 和 IAsyncResult 之间转换的文档

于 2013-01-26T13:37:51.803 回答