Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 804
philipp-fx Avatar asked Mar 15 '18 19:03

philipp-fx


1 Answers

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()
like image 95
Marc LaFleur Avatar answered Nov 17 '22 10:11

Marc LaFleur