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

前端 未结 3 1278
清歌不尽
清歌不尽 2020-12-06 15:58

The only override I see exposed on MVC\'s AuthorizeAttribute is public override void OnAuthorization( AuthorizationContext filterContext ) which is

相关标签:
3条回答
  • 2020-12-06 16:51

    ASP.NET MVC today does not support asynchronous filters. Please vote.

    However, ASP.NET "vNext", announced at TechEd this week, will support asynchronous filters for MVC.

    0 讨论(0)
  • 2020-12-06 16:53

    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.

    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. I added more detail about my solution here - http://evandontje.com/2017/08/15/solutions-for-async-await-in-mvc-action-filters/

    0 讨论(0)
  • 2020-12-06 17:05

    for those who do not yet have the joy of being on .net core, but you can use this method from ASP.NET Web API 2 :

    OnAuthorizationAsync override :

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

    for example you can call a async webapi service like this :

     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);
        }
    
    0 讨论(0)
提交回复
热议问题