Obtain strongly typed header class in ASP.NET Core
Asked Answered
I

1

21

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.

Involution answered 4/10, 2016 at 11:46 Comment(3)
Possible duplicate of Where all types for http headers gone in ASP.NET 5?Divergency
@Divergency 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.Involution
I posted this question as an issue on the GitHub project.Involution
I
23

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)) ...
Involution answered 18/1, 2017 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.