ASP.NET Core – 读写 Request / Response
需求
常见的需求就是从 request 里面读取一些 information. 比如
request URL, header, cookie,
写入 response header, cookie
实战
Razor Page Model 中
// 读取 request, header, cookie var fullUrl = HttpContext.Request.GetDisplayUrl(); // https://192.168.1.152:44300/?value=v1&value=v2 (note: about 的话是 .../about?value=v1, 不是 .../about/?value=v1 哦) var scheme = HttpContext.Request.Scheme; // https var host = HttpContext.Request.Host.Host; // 192.168.1.152 var port = HttpContext.Request.Host.Port; // 44300 var path = HttpContext.Request.Path; // "/" <-- home page 的 path 是 / var queryString = HttpContext.Request.QueryString.Value; // ?value=v1&value=v2 var query = HttpContext.Request.Query; if (query.TryGetValue("value", out StringValues value)) { // same key won't combine var value1 = value.ElementAt(0); // v1 var value2 = value.ElementAt(1); // v2 var combineValue = value.ToString(); // v1,v2 } var remoteIp = HttpContext.Connection.RemoteIpAddress; if (HttpContext.Request.Cookies.TryGetValue("cookie1", out var cookieValue)) { } var userAgent = HttpContext.Request.Headers.UserAgent.ToString(); var contentType = HttpContext.Request.Headers.ContentType.ToString(); if (HttpContext.Request.Headers.TryGetValue("Custom-Header", out StringValues customHeaderValue)) // h1,h2 { var h1 = customHeaderValue.ElementAt(0); // h1,h2 var h2 = customHeaderValue.ElementAtOrDefault(1); // null var combineHeader = customHeaderValue.ToString(); // h1,h2 // same key will combine become value1 value2 }; // 写入 header, cookie HttpContext.Response.Headers.Append("CustomResponseHeader", "value1"); HttpContext.Response.Cookies.Append("cookie1", "value1");
可以看到关键就是 HttpContext, request, response 都可以通过这个去读写.
header 和 query 如果遇到有 2 个 key (虽然我不知道什么情况下会需要这样), header 是会 combine value 而 query 是不会的哦
queryString 获取的值就是 original 的值, 是含 encode 的, 调用 TryGetValue 的时候我们则不需要顾虑 encode, decode, 它会替我们处理好.
更多关于 query 的操控可以看这篇
razor .cshtml
我们依然可以调用到 HttpContext
@HttpContext.Request.Headers.UserAgent
Web API Controller
var userAgent = HttpContext.Request.Headers.UserAgent;
DI Service
要在 service 中获取到 Httpcontext 就需要依赖注入.
首先在 startup.cs
services.AddHttpContextAccessor();
源码
然后在 Service.cs, 通过 HttpContextAccessor 就可以获取到 HttpContext 了
public class CustomerService { private readonly HttpContext _httpContext; public CustomerService( IHttpContextAccessor httpContextAccessor ) { _httpContext = httpContextAccessor.HttpContext!; } public string GetUserAgent() { return _httpContext.Request.Headers.UserAgent; } }
MVC View 中
Razor Pages 是 HttpContext 而 MVC VIew 是 Context 而已.