【转】ASP.NET Core 2.0中的HttpContext
ASP.NET Core 2.0中的HttpContext相较于ASP.NET Framework有一些变化,这边列出一些之间的区别。
在ASP.NET Framework中的 System.Web.HttpContext 对应 ASP.NET Core 2.0中的 Microsoft.AspNetCore.Http.HttpContext。
HttpContext
HttpContext.Items转换成:
IDictionary<object, object> items = httpContext.Items;
请求的唯一的ID:
string requestId = httpContext.TraceIdentifier;
HttpContext.Request
HttpContext.Request.HttpMethod 转换成:
string httpMethod = httpContext.Request.Method;
HttpContext.Request.QueryString 转换成:
IQueryCollection queryParameters = httpContext.Request.Query; // If no query parameter "key" used, values will have 0 items // If single value used for a key (...?key=v1), values will have 1 item ("v1") // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2") IList<string> values = queryParameters["key"]; // If no query parameter "key" used, value will be "" // If single value used for a key (...?key=v1), value will be "v1" // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2" string value = queryParameters["key"].ToString();
HttpContext.Request.Url 和 HttpContext.Request.RawUrl 转换成:
// using Microsoft.AspNetCore.Http.Extensions; var url = httpContext.Request.GetDisplayUrl();
HttpContext.Request.IsSecureConnection 转换成:
var isSecureConnection = httpContext.Request.IsHttps;
HttpContext.Request.UserHostAddress 转换成:
var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
HttpContext.Request.Cookies 转换成:
IRequestCookieCollection cookies = httpContext.Request.Cookies; string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception) string knownCookieValue = cookies["cookie1name"]; // will be actual value
HttpContext.Request.RequestContext.RouteData 转换成:
var routeValue = httpContext.GetRouteValue("key");
HttpContext.Request.Headers 转换成:
// using Microsoft.AspNetCore.Http.Headers; // using Microsoft.Net.Http.Headers; IHeaderDictionary headersDictionary = httpContext.Request.Headers; // GetTypedHeaders extension method provides strongly typed access to many headers var requestHeaders = httpContext.Request.GetTypedHeaders(); CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl; // For unknown header, unknownheaderValues has zero items and unknownheaderValue is "" IList<string> unknownheaderValues = headersDictionary["unknownheader"]; string unknownheaderValue = headersDictionary["unknownheader"].ToString(); // For known header, knownheaderValues has 1 item and knownheaderValue is the value IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage]; string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
HttpContext.Request.UserAgent 转换成:
string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
HttpContext.Request.UrlReferrer 转换成:
string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
HttpContext.Request.ContentType 转换成:
// using Microsoft.Net.Http.Headers; MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType; string contentType = mediaHeaderValue?.MediaType.ToString(); // ex. application/x-www-form-urlencoded string contentMainType = mediaHeaderValue?.Type.ToString(); // ex. application string contentSubType = mediaHeaderValue?.SubType.ToString(); // ex. x-www-form-urlencoded System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
HttpContext.Request.Form转换成:
if (httpContext.Request.HasFormContentType) { IFormCollection form; form = httpContext.Request.Form; // sync // Or form = await httpContext.Request.ReadFormAsync(); // async string firstName = form["firstname"]; string lastName = form["lastname"]; }
HttpContext.Request.InputStream 转换成:
string inputBody; using (var reader = new System.IO.StreamReader( httpContext.Request.Body, System.Text.Encoding.UTF8)) { inputBody = reader.ReadToEnd(); }
HttpContext.Response
HttpContext.Response.Status 和 HttpContext.Response.StatusDescription转换成:
// using Microsoft.AspNetCore.Http; httpContext.Response.StatusCode = StatusCodes.Status200OK;
HttpContext.Response.ContentEncoding 和 HttpContext.Response.ContentType 转换成:
// using Microsoft.Net.Http.Headers; var mediaType = new MediaTypeHeaderValue("application/json"); mediaType.Encoding = System.Text.Encoding.UTF8; httpContext.Response.ContentType = mediaType.ToString();
HttpContext.Response.ContentType 上其自身还转换成:
httpContext.Response.ContentType = "text/html";
HttpContext.Response.Output 转换成:
string responseContent = GetResponseContent(); await httpContext.Response.WriteAsync(responseContent);
HttpContext.Response.Headers
发送响应标头非常复杂,这一事实,如果任何内容都已写入响应正文将它们设置,它们将不发送。
解决方案是将设置将右之前调用写入响应启动的回调方法。 最好的做法是在开始 Invoke 中间件中的方法。 这是此回调方法,设置响应标头。
下面的代码设置调用的回调方法 SetHeaders :
public async Task Invoke(HttpContext httpContext) { // ... httpContext.Response.OnStarting(SetHeaders, state: httpContext); } // using Microsoft.AspNet.Http.Headers; // using Microsoft.Net.Http.Headers; private Task SetHeaders(object context) { var httpContext = (HttpContext)context; // Set header with single value httpContext.Response.Headers["ResponseHeaderName"] = "headerValue"; // Set header with multiple values string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" }; httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues; // Translating ASP.NET 4's HttpContext.Response.RedirectLocation httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com"; // Or httpContext.Response.Redirect("http://www.example.com"); // GetTypedHeaders extension method provides strongly typed access to many headers var responseHeaders = httpContext.Response.GetTypedHeaders(); // Translating ASP.NET 4's HttpContext.Response.CacheControl responseHeaders.CacheControl = new CacheControlHeaderValue { MaxAge = new System.TimeSpan(365, 0, 0, 0) // Many more properties available }; // If you use .Net 4.6+, Task.CompletedTask will be a bit faster return Task.FromResult(0); }
HttpContext.Response.Cookies
发送 cookie 需要用于发送响应标头以使用相同的回调:
public async Task Invoke(HttpContext httpContext) { // ... httpContext.Response.OnStarting(SetCookies, state: httpContext); httpContext.Response.OnStarting(SetHeaders, state: httpContext); }
SetCookies 回调方法将如下所示:
private Task SetCookies(object context) { var httpContext = (HttpContext)context; IResponseCookies responseCookies = httpContext.Response.Cookies; responseCookies.Append("cookie1name", "cookie1value"); responseCookies.Append("cookie2name", "cookie2value", new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true }); // If you use .Net 4.6+, Task.CompletedTask will be a bit faster return Task.FromResult(0); }
转自:https://www.jianshu.com/p/30796ccc6fcb
相关文章
- ASP.NET Core MVC请求超时设置解决方案
- ASP.NET Core MVC之Serilog日志处理,你了解多少?
- ASP.NET Core MVC压缩样式、脚本及总是复制文件到输出目录
- 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(完)
- 学习ASP.NET Core Blazor编程系列二十五——登录(4)
- 学习ASP.NET Core Blazor编程系列二十二——登录(1)
- 使用 ASP.NET Core MVC 创建 Web API(一)
- 学习ASP.NET Core Razor 编程系列十七——分组
- 浅谈Asp.net的sessionState
- ASp.net页面生存周期
- HTTP Error 500.31 - Failed to load ASP.NET Core runtime
- .NET Generic Host in ASP.NET Core
- Model validation in ASP.NET Core MVC and Razor Pages
- Understanding the ASP.NET MVC Execution Process
- ASP.NET Razor - C# and VB Code Syntax
- 二进制数据的序列化反序列化和Json的序列化反序列化的重要区别 <<C语言--神奇的指针>> 【1】Asp.Net Core2.2从环境配置到应用建立 加密解密帮助类 WebApi FromBody参数
- C# -- HttpWebRequest 和 HttpWebResponse 的使用 C#编写扫雷游戏 使用IIS调试ASP.NET网站程序 WCF入门教程 ASP.Net Core开发(踩坑)指南 ASP.Net Core Razor+AdminLTE 小试牛刀 webservice创建、部署和调用 .net接收post请求并把数据转为字典格式
- .NET Core实战项目之CMS 第二章 入门篇-快速入门ASP.NET Core看这篇就够了 [WPF]为旧版本的应用添加触控支持 js css等静态文件版本控制,一处配置多处更新.net版【原创】 C#图片处理,缩略图制作 SqlDataReader 结果集 转成 DataTable DataTable转成List集合 如何使用linq读取DataTable集合?
- Webservice WCF WebApi 前端数据可视化 前端数据可视化 C# asp.net PhoneGap html5 C# Where 网站分布式开发简介 EntityFramework Core依赖注入上下文方式不同造成内存泄漏了解一下? SQL Server之深入理解STUFF 你必须知道的EntityFramework 6.x和EntityFramework Cor
- ASP.NET Core知多少:路由重写及重定向
- 生成模板asp.net出现 CS1010: 常量中有换行符
- Asp.net变量与类型和类型转换示例(较全且完整,能直接运行!!)
- Asp.Net读取服务器EXE文件的方法!(超简单实例)
- ASP.NET Core应用程序容器化、持续集成与Kubernetes集群部署(二)
- ASP.NET Core应用程序的参数配置及使用
- ASP.NET压力测试
- 《精通 ASP.NET MVC 5》----1.8 本书所需的软件
- ASP.NET-自定义HttpModule与HttpHandler
- 三、ASP.NET Core 部署Linux
- Asp.Net Core MVC 中富文本编辑器CKEditor 5的配置及使用
- DevExtreme v 22.1 ASP.NET Core 应用程序项目,配置PivotGrid控件
- 理解 ASP.NET Core: 处理管道
- .net的简易多线程处理