zapoo
zapoo

Reputation: 1589

Web Api and where should I contorol Request Header data

In Asp.net Web Api, I want to control, request "access token" key is (which is in request header) valid or not. But I cound't decide where should I implement this kind of control. ActionFilter or controller constructor etc. etc.

Upvotes: 0

Views: 45

Answers (1)

Simon C
Simon C

Reputation: 9508

How about using a DelegatingHandler? It is part if the Web Api pipeline and executes before Routing and Controller handlers.

A really simple handler for access tokens may look like this. You would implement IsValid as you see fit.

public class ValidateTokenHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        var token = request.Headers.Authorization;
        if (token == null or !IsValid(token))
        {
            return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

Upvotes: 3

Related Questions