HttpContext
HttpContext 类封装了HTTP Request 和 HTTP Response。
当收到一条HTTP Request 请求时,就会实例化一个HttpContext对象。HttpContext对象可以被中间件访问。
注意:HttpContext 不是线程安全的。
读取 HttpContext 的值
从Razer Page 读取
public class IndexModel : PageModel
{
public void OnGet()
{
var message = HttpContext.Request.PathBase;
}
}
从Razer Page 的cshtml 读取
@page
@model IndexModel
@{
var message = HttpContext.Request.PathBase;
}
从 Controller 读取
public class HomeController : Controller
{
public IActionResult About()
{
var pathBase = HttpContext.Request.PathBase;
return View();
}
}
从 Minimal API 读取
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
例如下面的代码:
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
例子代码如下:
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 尾巴。
例子代码如下:文章来源:https://www.toymoban.com/news/detail-680887.html
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 已经被终止。
在请求时:文章来源地址https://www.toymoban.com/news/detail-680887.html
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();
到了这里,关于ASP.NET Core 的 HttpContex的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!