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

Time:01-04

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 havent 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);

Thank you in advance if anyone can help me on this!

CodePudding user response:

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

CodePudding user response:

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 ....
    }
}
  • Related