invaders7vn
invaders7vn

Reputation: 77

Checking Headers of a request before it goes to the controller in .NET Framework

I'm a currently trying to access the headers of my incoming requests to my API before it goes inside the controller and I want to check if it contains a specific headers. I've been looking for a way to implement a middleware or something like it but I haven't found any nice way to do it for web API using .net framework, I've only found solutions for .NET Core. Also I want to it globally for all my controllers to avoid adding something like this is every methods of my controllers:

(!Request.Headers.Contains(requiredHeader))
      return StatusCode(HttpStatusCode.PreconditionFailed);

Upvotes: 1

Views: 1528

Answers (2)

MD Zand
MD Zand

Reputation: 2605

Use DelegatingHandler like this:

public class MyCustomHeaderHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Check if the request contains the required header
        if (!request.Headers.Contains("requiredHeader"))
        {
            return request.CreateResponse(HttpStatusCode.PreconditionFailed);
        }

        // else, pass the request to the next handler in the pipeline
        return await base.SendAsync(request, cancellationToken);
    }
}

and register it in pipeline before others:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.MessageHandlers.Add(new MyCustomHeaderHandler());

        // Other configurations ....
    }
}

Upvotes: 1

T1Space
T1Space

Reputation: 81

Maybe you can use a base class that derives from Controller for all your controllers and add and override to OnActionExecuting.

Upvotes: 0

Related Questions