ASP.NET Core 中 HttpContext 详解与使用 | Microsoft.AspNetCore.Http 详解


笔者没有学 ASP.NET,直接学 ASP.NET Core ,学完 ASP.NET Core MVC 基础后,开始学习 ASP.NET Core 的运行原理。发现应用程序有一个非常主要的 “传导体” HttpContext

赶忙写一下笔记先。

目录

“传导体” HttpContext

操作 HttpContext 前期准备

HttpContext 类型的属性和方法

HttpContext 对象实践与测试

  • Request
  • Response
  • Item

Authentication               

这个已经用不到了,这里只是列一下表。

用于身份认证(ASP.NET中用到),官方不建议在ASP.NT Core中使用。替代方案 Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions

Connection

获取有关此请求的基础连接的信息

Features

获取此请求上可用的服务器和中间件提供的HTTP特性的集合

Items

获取或设置可用于在该请求范围内共享数据的键/值集合

Request

请求

RequestAborted

通知此请求基础的连接何时中止,因此请求操作应取消

RequestServices

获取或设置 IServiceProvider 集合,提供访问的请求的服务容器

Response

响应

Session

获取或设置用于管理此请求的用户会话数据的对象

TraceIdentifier

获取或设置用于在跟踪日志中表示此请求的唯一标识符

User

获取或设置此请求的用户

WebSockets

获取一个对象,该对象管理此请求的WebSu套连接的建立

Item、Session、Response 等对象都是需要经常使用到的,下面笔者会详细实践。


Body

获取或设置 RequestBody 流

ContentLength

获取或设置 Content-Length 头

ContentType

获取或设置Content-Type 头

Cookies

获取或设置 Cookies

Form

获取或设置 表单内容

HasFormContentType     

Checks the Content-Type header for form types.

Headers

Gets the request headers.

Host

获取或设置主机头。可以包括端口

HttpContext

获取或设置请求上下文

IsHttps

检测当前是否HTTPS连接

Method

获取或设置HTTP方法

Path

获取或设置当前请求的路径,即URL

PathBase

获取或设置 RequestPathBase,就是URL前面那一段,如https://docs.microsoft.com

Protocol

Gets or sets the RequestProtocol.

Query

查询字符串的集合

QueryString

获取或设置用于在Request.Query中创建查询集合的原始查询字符串

Scheme

获取或设置HTTP请求方案

试一试

打开 Index.Cshtml ,把以下代码加上去

(为了看得清楚一点,我加了表格)

RequestBody流 @Model.Request.Body
Content-Length头 @Model.Request.ContentLength
Content-Type头 @Model.Request.ContentType
Cookies @Model.Request.Cookies
IsHttps @Model.Request.IsHttps
Host @Model.Request.Host

运行Web程序,结果如下

在浏览器 F12 后,可以看到控制台的内容。请查看 下图的 1、3部分

Request 的其它使用方法,就不再赘述,你可以在视图中 @Model.Request. 加上需要测试的属性即可。

推荐别人关于 Request 的文章 https://www.cnblogs.com/Sea1ee/p/7240943.html


Body

获取或设置响应体流

ContentLength     

Gets or sets the value for the Content-Type response header.

ContentType

获取或设置内容类型响应标头的值

Cookies

获取一个对象,该对象可用于管理此响应的Cookie

HasStarted

Gets a value indicating whether response headers have been sent to the client.

Headers

Gets the response headers.

HttpContext

Gets the HttpContext for this response.

StatusCode

Gets or sets the HTTP response code.

Response 的方法

     OnCompleted(Func

在响应已发送到客户端之后添加要调用的委托

     OnCompleted(Func, Object)          

响应已发送到客户端之后添加要调用的委托

     OnStarting(Func)

在响应头将被发送到客户端之前添加要调用的委托

     OnStarting(Func, Object)

在响应头将被发送到客户端之前添加要调用的委托

     Redirect(String)

向客户端返回一个临时重定向响应(HTTP 302)

     Redirect(String, Boolean)

向客户端返回重定向响应(HTTP 301或HTTP 302)

     RegisterForDispose(IDisposable)

处置(不可分)在请求完成处理后,注册主机处理的对象                                                               

Response 拓展方法

GetTypedHeaders(HttpResponse)
WriteAsync(HttpResponse, String, Encoding, CancellationToken)

取消令牌使用给定的编码将给定文本写入响应体

WriteAsync(HttpResponse, String, CancellationToken)

将给定文本写入响应体。UTF-8编码将被使用

Clear(HttpResponse)
SendFileAsync(HttpResponse, IFileInfo, Int64, Nullable, CancellationToken)     

使用Sendfile 扩展发送给定的文件

SendFileAsync(HttpResponse, IFileInfo, CancellationToken)

Sends the given file using the SendFile extension.

SendFileAsync(HttpResponse, String, Int64, Nullable, CancellationToken)

Sends the given file using the SendFile extension.

SendFileAsync(HttpResponse, String, CancellationToken)

Sends the given file using the SendFile extension.

请参考下图的第 2 部分

Item

如果你使用过 ViewData,就不难理解 HttpContext.Item

HttpContext.Item 是一个字典集合类型,具体类型为 IDictionary。它的使用方法像 ViewData。(不要跟我说说你不知道 ViewBag、ViewData 是什么~)

 打开 Index.Cshtml ,用下面代码复制替换

@model Microsoft.AspNetCore.Http.HttpContext
@{
    Layout = null;
}
@{
    List<string> i = new List<string>();
    i.Add("a");
    i.Add("b");
    i.Add("c");
    i.Add("d");
    i.Add("e");
    i.Add("f");
    i.Add("g");
    i.Add("h");
    i.Add("i");

    Model.Items["Test"] = i;       
    /*
        Model.Items 是字典类型
        这里设置 键 Test
                 值 i ,它的值是 List 类型
    */

foreach(var item in Model.Items["Test"] as List<string>) //字典类型,必须先用 as 转为对应类型
{
    
@item } }

结果

 可以用 HttpContext.Item  来存储当前请求的意向有用的数据。


 HttpContext 的其它方法使用这里不再赘述,需要注意的是,HttpContext 是针对一个请求的而产生的。

相关