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

1

13

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.

Harte answered 15/3, 2018 at 19:28 Comment(6)
IHeaderDictionary implements IDictionary, you should be able to use all of the normal IDictionary APIs.Bertram
var contentType = headers["Content-Type"];Thissa
Possible duplicate of https://mcmap.net/q/264113/-how-to-extract-custom-header-value?Rectal
Thanks everyone for the great input! I think I was not clear enough with my question and rephrased it a little bit. The emphasis is on "all" headers and not only a few selected ones for which I must know the keys.Harte
Thanks to everyones input, I was able to get what I want. To get all the headers I needed to create a new Dictionary<string, StringValues> that takes the IHeaderDictionary as input, just like this: var headerDictionary = new Dictionary<string, StringValues>(headers)Harte
@Harte - you should answer your own question here and accept the answer. This trick is really useful, and most definitely not a duplicate of that other question :( - it's a shame the answer is muddle among the comments.Boulanger
R
14

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()
Reluctance answered 15/3, 2018 at 21:2 Comment(2)
Thanks for the answer Marc! Now I know how to extract headers for which I know the keys. This is already helpful, because I did not know how extract any key-value-pair header at all. Still, my goal is to extract all headers and I'd like to avoid the need to know all the keys.Harte
I was able to get what I want by creating a new dictionary that takes the headers variable as input. Thanks!Harte

© 2022 - 2024 — McMap. All rights reserved.