1

I'm trying to make my own custom System.Web.Http.AuthorizeAttribute. Everything was working until I needed to run some async function inside of the overridden OnAuthorizationfunction.

I found the OnAuthorizationAsync method and I use that, however still having issues running an async method. I need to ensure that a header attached to the HttpActionContext is in the db.

    public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        IEnumerable<string> values;
        if (actionContext.Request.Headers.TryGetValues("Authentication", out values))
        {
            var token = new Token() { TokenString = values.First() };
            if (await _tg.ValidateToken(token))
            {
                return base.OnAuthorizationAsync(actionContext, cancellationToken);
            }
        }

        base.HandleUnauthorizedRequest(actionContext);
    }

_tg.ValidateToken(token) is an async method that returns a bool. If I try to await it and make OnAuthorizationAsync an async method I then apparently cant return a Task:

Since OnAuthorizeAsync is an async method that returns 'Task', a return keyword must not be followed by an object expression.

Is there a way you can see out of this mess?

2 Answers 2

4

Because you use await, you need to add the async modifier to the method's declaration. Then change the return you have there to await. The compiler will do the rest - i.e. returning the Task for you.

Sign up to request clarification or add additional context in comments.

1 Comment

@Nick H, should mark this answer as valid if it works for you
2

Based on @sellotape's answer:

public async override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
    IEnumerable<string> values;
    if (actionContext.Request.Headers.TryGetValues("Authentication", out values))
    {
        var token = new Token() { TokenString = values.First() };
        if (await _tg.ValidateToken(token))
        {
            return await base.OnAuthorizationAsync(actionContext, cancellationToken);
        }
    }
    await base.HandleUnauthorizedRequest(actionContext);
}

1 Comment

This is not complete. You need to await base.OnAuthorizationAsync, not return it. don't just pass the Task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.