OdeToCode IC Logo

Working With Typed Headers in ASP.NET

Monday, November 30, 2015

Inside of a controller in ASP.NET 5, the Request and Response properties both give you access to a Headers property. Headers is a simple IHeaderDictionary and will ultimately hand out string values.

Bring in the Microsoft.AspNet.Http namespace and you'll find a GetTypedHeaders extension method available for both Request and Response. Instead of working with raw strings, this extension method allows you to work with classes like MediaTypeHeaderValue, proper numbers, and strong types in general. 

var requestHeaders = Request.GetTypedHeaders();
var responseHeaders = Response.GetTypedHeaders();

var mediaType = requestHeaders.Accept[0].MediaType;
long? length = responseHeaders.ContentLength;

// ...