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();