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. FTP的vsftpd.conf含义

    # 设置为YES时vsftpd以独立运行方式启动,设置为NO时以xinetd方式启动 #(xinetd是管理守护进程的,将服务集中管理,可以减少大量服务的资源消耗) listen=YES # 同上,如 ...

  2. Java中进行Md5加密

    java文件 https://pan.baidu.com/s/1kXcif35  密码:3cjd 代码案例: package cn.itcast.estore.utils; import java.m ...

  3. PaperReading20200221

    CanChen ggchen@mail.ustc.edu.cn Busy... Human-level concept learning through probabilistic program i ...

  4. kafka-console-consumer接收不到flume推送过来的消息

    原因和解决方法:需要先启动kafka,再启动flume,两者启动有先后顺序.

  5. ASP.NET MVC 4 中Razor 视图中JS无法调试 (重要)

    谷歌浏览器,firefox,IE 都可以 1.首先检查IE中这2个属性是否勾选了. 2.选择IE浏览器进行调试,调试方法有2种 A:采用debugger;的方法,如下图所示: 这时不用调试断点就会在d ...

  6. 项目启动异常,java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

    java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' befo ...

  7. 在vnware中配置好redis后,不能使用图形化工具打开

    1.先检查防火墙的状态 通过systemctl status firewalld查看firewalld状态,发现当前是dead状态,即防火墙未开启 通过systemctl start firewall ...

  8. luogu P2756 飞行员配对方案问题(Dinic板子)

    建立一个超级源点,将每个外籍飞行员连一条capacity为1的路,一个超级汇点,每个英国飞行员也连一条capacity为1的路,根据读入在英国飞行员和外籍飞行员连接capacity为1的路,匹配方案就 ...

  9. Day10:关于桃子的和关于游戏新的设想(顺手做个记录孩子吃喝拉撒的工具)

    公历2015年6月3日~ 北京时间晚上8:42~ 在美中宜和~ 一个叫桃子的小美女出生了! 没错!小桃子终于出生了!真心不容易啊! 6月3日 03:00 AM 老婆推我,叫我起来,她说她肚子疼,还想上 ...

  10. pip 安装源

    pip 安装源 介绍 1.采用国内源,加速下载模块的速度 2.常用pip源: -- 豆瓣:https://pypi.douban.com/simple -- 阿里:https://mirrors.al ...