简体   繁体   English

是否可以在 MVC 4 AuthorizeAttribute 中使用异步/等待?

[英]Is it possible to use async/await in MVC 4 AuthorizeAttribute?

The only override I see exposed on MVC's AuthorizeAttribute is public override void OnAuthorization( AuthorizationContext filterContext ) which is not suitable for use with async/await because it doesn't return a Task .我在 MVC 的AuthorizeAttribute上看到的唯一覆盖是public override void OnAuthorization( AuthorizationContext filterContext ) ,它不适合与 async/await 一起使用,因为它不返回Task Is there another way to create an AuthorizeAttribute in MVC that allows the use of async/await?是否有另一种方法可以在 MVC 中创建允许使用 async/await 的AuthorizeAttribute

ASP.NET MVC today does not support asynchronous filters.今天的 ASP.NET MVC 不支持异步过滤器。 Please vote .请投票

However, ASP.NET "vNext" , announced at TechEd this week, will support asynchronous filters for MVC.然而,本周在 TechEd 上宣布的ASP.NET "vNext"将支持 MVC 的异步过滤器。

With asp.net core being released, Stephen Cleary's answer is correct and the ideal way to go if you are running the latest asp.net core.随着 asp.net 核心的发布,Stephen Cleary 的回答是正确的,如果您正在运行最新的 asp.net 核心,这是理想的方式。

For those that haven't updated yet, I was able to work around my issue using an async HttpModule that passes state into the AuthorizationFilter via HttpContext.Items .对于那些尚未更新的人,我能够使用异步 HttpModule 解决我的问题,该异步 HttpModule 通过HttpContext.Items将状态传递给 AuthorizationFilter。 I added more detail about my solution here - http://evandontje.com/2017/08/15/solutions-for-async-await-in-mvc-action-filters/我在这里添加了有关我的解决方案的更多详细信息-http: //evandontje.com/2017/08/15/solutions-for-async-await-in-mvc-action-filters/

For those who do not yet have the joy of being on .NET core, you can use this method from ASP.NET Web API 2 :对于那些还没有使用 .NET core 的人,您可以使用 ASP.NET Web API 2 中的这个方法:

OnAuthorizationAsync override : OnAuthorizationAsync 覆盖:

public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)

for example, you can call an async webapi service like this :例如,您可以像这样调用异步webapi 服务:

 public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)
    {
        await base.OnAuthorizationAsync(actionContext, cancellation);

        if (await IsUserAdminAsync()) /* call any async service */
            return;
        this.HandleUnauthorizedRequest(actionContext);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM