Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where all types for http headers gone in ASP.NET 5?

Previously, in WebApi (on .NET 4.x) we could work with headers of both the request and the response via typed interfaces (see HttpRequestMessage.Headers/HttpResponseMessage.Headers). Now, in ASP.NET 5 we have HttpRequest and HttpResponse with Headers property of type IHeaderDictionary. But it's just an untyped Dictionary.

Below I put an example with typed accessing could return a fine-tuned http-response. It's needed to create a HttpResponseMessage and fill its Headers collection (which was typed btw).

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(manifestContent);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/cache-manifest");
response.Headers.CacheControl = new CacheControlHeaderValue {NoCache = true, Public = true};
response.Headers.ETag = new EntityTagHeaderValue("\"" + etag + "\"");
like image 650
Shrike Avatar asked Apr 17 '15 18:04

Shrike


People also ask

How do I read request headers in .NET core?

Using the [FromQuery] and [FromHeader] attributes in ASP.NET Core 5 MVC. ASP.NET Core introduces the [FromQuery] and [FromHeader] attributes. While the former is used to pass data via query strings, the latter is used to pass data to the action methods of your controller using request headers.

What are headers in HTTP requests?

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.


2 Answers

If you add the using statement for Microsoft.AspNetCore.Http, there are extension methods on the HttpRequest and HttpResponse to GetTypedHeaders, which should give you the type safety that you want.

In the example, I also added the using statement for Microsoft.Net.Http.Headers, just to clean it up.

var headers = Response.GetTypedHeaders();
headers.ContentType = new MediaTypeHeaderValue("text/cache-manifest");
headers.CacheControl = new CacheControlHeaderValue { NoCache = true, Public = true };
headers.ETag = new EntityTagHeaderValue("\"" + etag + "\"");

Source: aspnet/HttpAbstractions on Github

like image 68
Matt DeKrey Avatar answered Sep 16 '22 16:09

Matt DeKrey


In Asp.net 5 the headers collection is now a single class i.e. HeaderDictionary that can be used for both request and response headers. This will act as a key value based store for headers. The good reason I can see is because of Owin support. One store can be used utilized across various Owin supported middleware e.g. WebApi, SignalR which provides you extensibility for adding more information in Header collection.

like image 42
vendettamit Avatar answered Sep 18 '22 16:09

vendettamit