When does WebApi2 use OnAuthorizationAsync vs OnAuthorization

前端 未结 1 1400
南方客
南方客 2021-02-14 12:15

We\'ve recently implemented API authentication by implementing a custom AuthorizationFilterAttribute, using credentials stored in Azure Document DB. DocDB mandates everything u

相关标签:
1条回答
  • 2021-02-14 12:42

    If you take a look at the source code of AuthorizationFilterAttribute then you can see that the base implementation of OnAuthorizationAsync is the one actually calling OnAuthorization.

    public virtual void OnAuthorization(HttpActionContext actionContext)
    {
    }
    
    public virtual Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        try
        {
            OnAuthorization(actionContext);
        }
        catch (Exception ex)
        {
            return TaskHelpers.FromError(ex);
        }
    
        return TaskHelpers.Completed();
    }
    

    As you can see, you can actually override either method you want and you don't need to call the base implementation. Just choose the one which makes more since for your scenario - it doesn't matter if the controller is async or not.

    And regarding your question about marking OnAuthorization itself as async - the code compiles since that's the way C# async support is designed, but it indeed causes the calling code to not wait for the async part to complete (it actually can't wait since the method is marked async void and not async Task. You can read more about async avoid here.

    0 讨论(0)
提交回复
热议问题