哪个http头的类型在ASP.NET 5中消失了?

Shr*_*ike 13 c# asp.net-core-mvc asp.net-core

以前,在WebApi(在.NET 4.x上),我们可以通过类型化接口处理请求和响应的头文件(请参阅HttpRequestMessage.Headers/ HttpResponseMessage.Headers).现在,在ASP.NET 5,我们有HttpRequestHttpResponse同类型的标题属性IHeaderDictionary.但它只是一个无类字典.

下面我给一个带有类型访问的例子可以返回一个微调的http响应.需要创建HttpResponseMessage并填充其Headers集合(键入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 + "\"");
Run Code Online (Sandbox Code Playgroud)

Mat*_*rey 16

如果你添加using语句Microsoft.AspNetCore.Http,那么在HttpRequestHttpResponseto 上有扩展方法GetTypedHeaders,它们可以为你提供所需的类型安全性.

在这个例子中,我还添加了using语句Microsoft.Net.Http.Headers,只是为了清理它.

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

资料来源:Github上的aspnet/HttpAbstractions