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

此生再无相见时 提交于 2020-01-21 10:38:47

问题


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 + "\"");

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/29706719/where-all-types-for-http-headers-gone-in-asp-net-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!