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. Python 爬取 北京市政府首都之窗信件列表-[后续补充]

    日期:2020.01.23 博客期:131 星期四 [本博客的代码如若要使用,请在下方评论区留言,之后再用(就是跟我说一声)] //博客总体说明 1.准备工作 2.爬取工作(本期博客) 3.数据处理 ...

  2. uni app中使用自定义图标库

    项目中难免会用到自定义图标,那在uni app中应该怎么使用呢? 首先, 将图标目录放在static资源目录下: 在main.js中引入就可以全局使用了 import '@/static/icon-o ...

  3. MariaDB——日志文件

    数据库各类日志  查询日志:   记录每一条sql语句,建议不开启,因为如果访问量过大,会占用相当大的资源,影响数据库的性能.    vim /etc/my.cnf.d/server.cnf    g ...

  4. Day9 - K - Yue Fei's Battle HDU - 5136

    Yue Fei is one of the most famous military general in Chinese history.He led Southern Song army in t ...

  5. HDU-1312题解(DFS)

    HDU-1312-DFS Written by Void-Walker    2020-02-01 09:09:25 1.题目传送门:http://acm.hdu.edu.cn/showproblem ...

  6. GSON使用笔记(3) -- 如何反序列化出List

    GSON使用笔记(3) -- 如何反序列化出List 时间 2014-06-26 17:57:06  CSDN博客原文  http://blog.csdn.net/zxhoo/article/deta ...

  7. Java注解浅谈

    注解定义(来自百度百科):指示编译器如何对待您的自定义 Annotation,预设上编译器会将Annotation资讯留在class档案中,但不被虚拟机器读取,而仅用于编译器或工具程式运行时提供资讯. ...

  8. VS中MFC项目文件特别大的解决办法

    转 来自http://m.zhizuobiao.com/vc/vc-18082800177/ 自己插个眼 项目文件比较大因为 项目下有个隐藏文件夹.vs  下面是解决办法 本文主要向大家介绍了VC编程 ...

  9. 配置antMatchers(HttpMethod.GET,"/**").permitAll()当时仍然会校验

    .antMatchers(HttpMethod.GET,"/**").permitAll() .anyRequest().authenticated() .and() .addFi ...

  10. 蓝牙 BLE 协议学习: 3种蓝牙架构实现方案(蓝牙协议栈方案)

    导言 不同的蓝牙架构可以用在不同的场景中.从而协议帧的架构方案也会不同. 转载自:<三种蓝牙架构实现方案(蓝牙协议栈方案)> 蓝牙架构实现方案有哪几种?我们一般把整个蓝牙实现方案叫做蓝牙协 ...