async action filter: Async & AuthorizeAttribute in ASP.NET WEB API

ay.metallo picture ay.metallo · Oct 19, 2012 · Viewed 8k times · Source

I have my authentication logic in a class, derived from System.Web.Http.AuthorizeAttribute (overridden OnAuthorization method). I make a call to a DB from that method and I want that call to be asynchronous (luckily, the new ADO.NET async API allows that).

Then I apply this attribute to a controller to have all calls to it go thru the authentication filter. So far so good.

But doing so I run into the following problem. The framework (ASP.NET Web API) doesn't seem to be aware of what my intentions are :) It looks like it proceeds with the controller's action execution before my filter's OnAuthorizaion methods finishes (returns from the async call).. Hence the exception from the framework a la "request processing finished before all the outstanding async operations are complete.."

Is there any out-of-the-box way to deal with that?

Thanks!

P.S. My gut feeling says that I'm in for a custom action filter creation.. Then I'll need to override ExecuteActionFilterAsync and do my authentication there handling all the Task-related stuff myself with no help from the framework side.. )

Answer

Guo Huang picture Guo Huang · Oct 18, 2018

Use IAsyncAuthorizationFilter and implement the interface asynchronously.

public async Task OnAuthorizationAsync(AuthorizationFilterContext actionContext)