How do you obtain a strongly typed header class from the namespace System.Net.Http.Headers from an ASP.NET Core controller? In a controller derived from Controller, Request.Headers is available, but it just returns IHeaderDictionary. There is also an extension method HeaderDictionaryTypeExtensions.GetTypedHeaders, but it returns RequestHeaders, which has only certain headers. The class HttpRequestHeaders has the most comprehensive list of headers, but it's not clear how to access it.
For example, how would you get a AuthenticationHeaderValue? One option is AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]), but that requires hard coding the header name. Perhaps there is a non-hard-coded way to get to HttpRequestHeaders.Authorization.
This has been a stumper on StackOverflow since October. Is this possible? Is it perhaps something that should be improved in the project?
@Tratcher thoughts on this? I'm guessing the answer is that there's no simple way...
There are a few ways to do this. GetTypedHeaders is the recommended way, though it doesn't include AuthenticationHeaderValue. We excluded AuthenticationHeaderValue because it did not provide meaningful parsing beyond the normal header comma splitting GetCommaSeperatedValues. Do you actually need a AuthenticationHeaderValue instance?
If you're worried about hard coding the header names we have constants for those. See HeaderNames.Authorization:
https://github.com/aspnet/HttpAbstractions/blob/87cd79d6fc54bb4abf07c1e380cd7a9498a78612/src/Microsoft.Net.Http.Headers/HeaderNames.cs
HeaderNames solves the hard coded string problem. For some reason, IntelliSense is really bad at guessing what I'm going to type into a string. :-)
The cherry picking in RequestHeaders still seems disjointed. It's not clear why AuthenticationHeaderValue is valuable enough to exist, but not valuable enough to include in RequestHeaders. Perhaps the parse method has more worth than its first seems: just knowing that the parts are comma delimited is a nice detail to encapsulate.
You asked if I needed AuthenticationHeaderValue. In my code, I knew I had an authentication header coming in that could have an X-ApiKey scheme or could have a Basic scheme. I appreciated how with AuthenticationHeaderValue I didn't have to look at the RFC; I simply used Scheme and Parameter, and it did the right thing. If there was a similar helper for parsing the Basic scheme's parameter, I would have used that, too.
We are closing this issue because no further action is planned for this issue. If you still have any issues or questions, please log a new issue with any additional details that you have.