问题描述
以前,在WebApi(在.NET 4.x上)中,我们可以通过类型化的接口使用请求和响应的标头(请参见HttpRequestMessage.Headers
/HttpResponseMessage.Headers
).现在,在ASP.NET 5中,我们具有HttpRequest
和HttpResponse
,其Headers属性的类型为IHeaderDictionary
.但这只是一个无类型的字典.
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.
下面,我举一个带有类型化访问的示例,它可以返回经过微调的http响应.需要创建一个HttpResponseMessage
并填充其Headers集合(键入btw).
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 + "\"");
推荐答案
如果为Microsoft.AspNetCore.Http
添加using语句,则HttpRequest
和HttpResponse
到GetTypedHeaders
上都有扩展方法,应该可以给您您想要的类型安全性.
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.
在示例中,我还为Microsoft.Net.Http.Headers
添加了using语句,只是为了清理它.
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 + "\"");
来源: aspnet/HttpAbstractions on GitHub
这篇关于在ASP.NET 5中,HTTP标头的所有类型都在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!