ASP.Net Core 2.0 How to get all request headers in middleware?

25.8k Views Asked by At

In ASP.Net Core 2.0, I am trying to validate the incoming request headers in a custom middleware.

The problem is that I don't how to extract all the key-value-pair headers. The headers that I need are stored in a protected property

protected Dictionary<string, stringValues> MaybeUnknown

My middleware class looks like this so far:

public class HeaderValidation
{
    private readonly RequestDelegate _next;
    public HeaderValidation(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        IHeaderDictionary headers = httpContext.Request.Headers; // at runtime headers are of type FrameRequestHeaders

        // How to get the key-value-pair headers?
        // "protected Dictionary<string, stringValues> MaybeUnknown" from headers is inaccessbile due to its protection level
        // Casting headers as Dictionary<string, StringValues> results in null

        await _next.Invoke(httpContext);
    }
}

My goal is to extract all request headers and not only a few selected headers for which I must know the specific keys.

1

There are 1 best solutions below

2
On

httpContext.Request.Headers is a Dictionary. You can return the value of a header by passing the header name as the key:

context.Request.Headers["Connection"].ToString()