ASP.NET Core 的 HttpContex

HttpContext

HttpContext 类封装了HTTP Request 和 HTTP Response。

当收到一条HTTP Request 请求时,就会实例化一个HttpContext对象。HttpContext对象可以被中间件访问。

注意:HttpContext 不是线程安全的。

读取 HttpContext 的值

从Razer Page 读取

csharp 复制代码
public class IndexModel : PageModel
{
    public void OnGet()
    {
        var message = HttpContext.Request.PathBase;
    }
}

从Razer Page 的cshtml 读取

html 复制代码
@page
@model IndexModel
@{
    var message = HttpContext.Request.PathBase;
}

从 Controller 读取

csharp 复制代码
public class HomeController : Controller
{
    public IActionResult About()
    {
        var pathBase = HttpContext.Request.PathBase;
        return View();
    }
}

从 Minimal API 读取

csharp 复制代码
app.MapGet("/", (HttpContext context) => context.Response.WriteAsync("Hello World"));

修改 HttpContext.Request

HttpContext.Request 可以获取客户端发来的 HttpRequest 请求,并且可以修改其中的值,包括:

  • HttpRequest.Path
  • HttpRequest.Method
  • HttpRequest.Headers
  • HttpRequest.RouteValues
  • HttpRequest.Query
  • HttpRequest.ReadFormAsync()
  • HttpRequest.Body

例如下面的代码:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", (HttpRequest request) =>
{
    var userAgent = request.Headers.UserAgent;
    var customHeader = request.Headers["x-custom-header"];
    return Results.Ok(new { userAgent = userAgent, customHeader = customHeader });
});

app.Run();

修改 HttpContext.Response

除了能修改接收到的 HttpRequest,返回给客户端的 Response也可以修改。包括:

  • HttpResponse.StatusCode
  • HttpResponse.ContentType
  • HttpResponse.Headers
  • HttpResponse.Body

例子代码如下:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", (HttpResponse response) =>
{
    response.Headers.CacheControl = "no-cache";
    response.Headers["x-custom-header"] = "Custom value";
    return Results.File(File.OpenRead("helloworld.txt"));
});

app.Run();

设置 Response 尾巴

HTTP/2 和 HTTP/3 支持 Response 尾巴,可以在返回 Response 后设置Response 尾巴。

例子代码如下:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", (HttpResponse response) =>
{
    // Write body
    response.WriteAsync("Hello world");
    if (response.SupportsTrailers())
    {
        response.AppendTrailer("trailername", "TrailerValue");
    }
});
app.Run();

终止 HttpRequest

HttpContext.RequestAborted cancellation token 可以用于通知HttpRequest 已经被终止。

在请求时:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var httpClient = new HttpClient();
app.MapPost("/books/{bookId}", async (int bookId, HttpContext context) =>
{
    var stream = await httpClient.GetStreamAsync(
        $"http://consoto/books/{bookId}.json", context.RequestAborted);
    return Results.Stream(stream, "application/json");
});
app.Run();
相关推荐
掘金者阿豪1 小时前
终于!我的第二本书正式出版,吃透 Agentic AI 核心不踩坑
javascript·后端
二月龙1 小时前
Redis 缓存设计避坑指南:穿透、击穿、雪崩与一致性问题
后端
掘金者阿豪1 小时前
运营不会SQL怎么办?我把数据库变成了大家都会用的表格
后端
孟陬1 小时前
国外技术周刊 #139:LLM 正在杀死程序员的「懒惰美德」
前端·人工智能·后端
七牛云行业应用1 小时前
Codex CLI 和 Codex 桌面端完整教程:两种入口的功能对比与选择指南
前端·后端·github
wheninger1 小时前
DDD 聚合 × Agent 命令:那道拒绝 AI 的墙
后端
狂炫冰美式1 小时前
AI 生成 Draw.io,导入飞书/Lark 画板后可编辑
前端·人工智能·后端
浩风祭月1 小时前
一个开发者的“看门狗”:我把服务器监控从被动告警变成了主动预防
后端·docker
Moment1 小时前
我做了一套前端也能学懂的 AI Agent 系列,从 Prompt 一路讲到多 Agent 😍😍😍
前端·后端·面试
terry6002 小时前
从流畅交互到高可用:企讯通Qcaptcha滑动拼图的毫秒级响应与容灾设计
web安全·json·asp.net·信息与通信·数据库架构