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 2.0中的HttpContext的更多相关文章

  1. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  2. 在ASP.NET Core 1.0中如何发送邮件

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...

  3. ASP.NET Core 1.0 中使用 Swagger 生成文档

    github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...

  4. 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...

  5. 在ASP.NET Core 2.0中使用CookieAuthentication

    在ASP.NET Core中关于Security有两个容易混淆的概念一个是Authentication(认证),一个是Authorization(授权).而前者是确定用户是谁的过程,后者是围绕着他们允 ...

  6. 如何在ASP.NET Core 2.0中使用Razor页面

    如何在ASP.NET Core 2.0中使用Razor页面  DotNetCore2017-11-22 14:49 问题 如何在ASP.NET Core 2.0中使用Razor页面 解 创建一个空的项 ...

  7. ASP.NET Core 3.0中使用动态控制器路由

    原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...

  8. asp.net core 3.0 中使用 swagger

    asp.net core 3.0 中使用 swagger Intro 上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口 ...

  9. 探索 ASP.Net Core 3.0系列三:ASP.Net Core 3.0中的Service provider validation

    前言:在本文中,我将描述ASP.NET Core 3.0中新的“validate on build”功能. 这可以用来检测您的DI service provider是否配置错误. 具体而言,该功能可检 ...

随机推荐

  1. 微信小程序(基础)

    文档官网:https://developers.weixin.qq.com/miniprogram https://developers.weixin.qq.com/miniprogram/dev/f ...

  2. 六、java基础-单例模式_继承_覆盖_多态

    1.单例模式: 1)提出原因 是由gof 也就是四人组提出来的.为了保证jvm中某一类型的java对象永远只有一个,同时也是为了节省内存的开销.因为外面程序可以通过new的方法直接调用类里面的构造方法 ...

  3. 如何在Java中测试类是否是线程安全的

    通过优锐课的java核心笔记中,我们可以看到关于如何在java中测试类是否线程安全的一些知识点汇总,分享给大家学习参考. 线程安全性测试与典型的单线程测试不同.为了测试一个方法是否是线程安全的,我们需 ...

  4. Commons BeanUtils 中对Map的操作

    CSDN学院招募微信小程序讲师啦 程序员简历优化指南! [观点]移动原生App开发 PK HTML 5开发 云端应用征文大赛,秀绝招,赢无人机! Commons BeanUtils 中对Map的操作 ...

  5. ie brower 点击用默认浏览器打开链接

    <script> function GetCurrentJumpUrl(){ var eleLink = document.getElementById('adLink'); if(ele ...

  6. Myeclipse项目出现红叉解决方案

    1.右键点击你的项目.选中properties 2.选中MyEclipse下的Project Facets里面的java 此时的版本号为1.5,修改 3.选中MyEclipse下的Project Fa ...

  7. hibernate部分源码解析and解决工作上关于hibernate的一个问题例子(包含oracle中新建表为何列名全转为大写且通过hibernate取数时如何不用再次遍历将列名(key)值转为小写)

    最近在研究系统启动时将数据加载到内存非常耗时,想着是否有办法优化!经过日志打印测试发现查询时间(查询时间:将数据库数据查询到系统中并转为List<Map>或List<*.Class& ...

  8. linux下mysql允许远程连接

    1. MySql安装教程 https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html 默认情况下mysq的 roo ...

  9. Samjia 和矩阵[loj6173](Hash+后缀数组)

    传送门 本题要求本质不同的子矩阵,即位置不同也算相同(具体理解可以看样例自己yy). 我们先看自己会什么,我们会求一个字符串中不同的子串的个数.我们考虑把子矩阵变成一个字符串. 先枚举矩阵的宽度,记为 ...

  10. springboot项目启动报错 Failed to configure a DataSource: 'url' attribute is not specified and no embedde

    参考:https://blog.csdn.net/Coyotess/article/details/80637837