Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain strongly typed header class in ASP.NET Core

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.

like image 325
Edward Brey Avatar asked Oct 04 '16 11:10

Edward Brey


1 Answers

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)) ...
like image 168
Edward Brey Avatar answered Oct 21 '22 18:10

Edward Brey