Pergunta

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. Is there another way to create an AuthorizeAttribute in MVC that allows the use of async/await?

Foi útil?

Solução

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.

Outras dicas

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/

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 :

OnAuthorizationAsync override :

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

for example, you can call an 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);
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top