Where all types for http headers gone in ASP.NET 5?(ASP.NET 5 中所有类型的 http 标头都去了哪里?)
问题描述
以前,在 WebApi(在 .NET 4.x 上)中,我们可以通过类型化接口处理请求和响应的标头(请参阅 HttpRequestMessage.Headers/HttpResponseMessage.Headers代码>).现在,在 ASP.NET 5 中,我们有 HttpRequest 和 HttpResponse 以及类型为 IHeaderDictionary 的 Headers 属性.但它只是一个无类型的字典.
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-response.需要创建一个 HttpResponseMessage 并填充其 Headers 集合(顺便说一句).
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 onGithub
这篇关于ASP.NET 5 中所有类型的 http 标头都去了哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET 5 中所有类型的 http 标头都去了哪里?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
