17

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.

Edward Brey
  • 35,877
  • 14
  • 173
  • 224
  • Possible duplicate of [Where all types for http headers gone in ASP.NET 5?](http://stackoverflow.com/questions/29706719/where-all-types-for-http-headers-gone-in-asp-net-5) – Tseng Oct 06 '16 at 01:06
  • @Tseng That other question has an accepted answer based on the `RequestHeaders`, which is useful for some headers, but not others. This question focuses on how to get the more comprehensive `HttpRequestHeaders` available in ASP.NET Core 1.0. – Edward Brey Oct 07 '16 at 07:37
  • I posted this question as an issue on the [GitHub project](https://github.com/aspnet/Mvc/issues/5680). – Edward Brey Jan 12 '17 at 17:50

1 Answers1

19

Use AuthenticationHeaderValue to parse the header string into an object with Scheme and Parameter properties.

var auth = AuthenticationHeaderValue.Parse(Request.Headers[HeaderNames.Authorization]);

if (auth.Scheme != expectedScheme || !MyVerifyAuthParamteter(auth.Parameter)) ...
Edward Brey
  • 35,877
  • 14
  • 173
  • 224