ASP.NET Core 2.0中的HttpContext
2021-02-19 22:19
标签:tpm rop headers color display cookie header 自身 redirect ??ASP.NET Core 2.0中的HttpContext相较于ASP.NET Framework有一些变化,这边列出一些之间的区别。 ??在ASP.NET Framework中的 System.Web.HttpContext 对应 ASP.NET Core 2.0中的 Microsoft.AspNetCore.Http.HttpContext。 ??HttpContext.Items转换成: ??请求的唯一的ID: ??HttpContext.Request.HttpMethod 转换成: ??HttpContext.Request.QueryString 转换成: ??HttpContext.Request.Url 和 HttpContext.Request.RawUrl 转换成: ??HttpContext.Request.IsSecureConnection 转换成: ??HttpContext.Request.UserHostAddress 转换成: ??HttpContext.Request.Cookies 转换成: ??HttpContext.Request.RequestContext.RouteData 转换成: ??HttpContext.Request.Headers 转换成: ??HttpContext.Request.UserAgent 转换成: ??HttpContext.Request.UrlReferrer 转换成: ??HttpContext.Request.ContentType 转换成: ??HttpContext.Request.Form转换成: ??HttpContext.Request.InputStream 转换成: ??HttpContext.Response.Status 和 HttpContext.Response.StatusDescription转换成: ??HttpContext.Response.ContentEncoding 和 HttpContext.Response.ContentType 转换成: ??HttpContext.Response.ContentType 上其自身还转换成: ??HttpContext.Response.Output 转换成: HttpContext.Response.Headers HttpContext.Response.Cookies ??SetCookies 回调方法将如下所示: ASP.NET Core 2.0中的HttpContext 标签:tpm rop headers color display cookie header 自身 redirect 原文地址:https://www.cnblogs.com/lonelyxmas/p/12923012.html说明:参考微软官方文档。
HttpContext
IDictionaryobject, object> items = httpContext.Items;
string requestId = httpContext.TraceIdentifier;
HttpContext.Request
string httpMethod = httpContext.Request.Method;
IQueryCollection queryParameters = httpContext.Request.Query;
// If no query parameter "key" used, values will have 0 items
// If single value used for a key (...?key=v1), values will have 1 item ("v1")
// If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
IListstring> values = queryParameters["key"];
// If no query parameter "key" used, value will be ""
// If single value used for a key (...?key=v1), value will be "v1"
// If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
string value = queryParameters["key"].ToString();
// using Microsoft.AspNetCore.Http.Extensions;
var url = httpContext.Request.GetDisplayUrl();
var isSecureConnection = httpContext.Request.IsHttps;
var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
IRequestCookieCollection cookies = httpContext.Request.Cookies;
string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
string knownCookieValue = cookies["cookie1name"]; // will be actual value
var routeValue = httpContext.GetRouteValue("key");
// using Microsoft.AspNetCore.Http.Headers;
// using Microsoft.Net.Http.Headers;
IHeaderDictionary headersDictionary = httpContext.Request.Headers;
// GetTypedHeaders extension method provides strongly typed access to many headers
var requestHeaders = httpContext.Request.GetTypedHeaders();
CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
// For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
IListstring> unknownheaderValues = headersDictionary["unknownheader"];
string unknownheaderValue = headersDictionary["unknownheader"].ToString();
// For known header, knownheaderValues has 1 item and knownheaderValue is the value
IListstring> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
// using Microsoft.Net.Http.Headers;
MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
string contentType = mediaHeaderValue?.MediaType.ToString(); // ex. application/x-www-form-urlencoded
string contentMainType = mediaHeaderValue?.Type.ToString(); // ex. application
string contentSubType = mediaHeaderValue?.SubType.ToString(); // ex. x-www-form-urlencoded
System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
if (httpContext.Request.HasFormContentType)
{
IFormCollection form;
form = httpContext.Request.Form; // sync
// Or
form = await httpContext.Request.ReadFormAsync(); // async
string firstName = form["firstname"];
string lastName = form["lastname"];
}
string inputBody;
using (var reader = new System.IO.StreamReader(
httpContext.Request.Body, System.Text.Encoding.UTF8))
{
inputBody = reader.ReadToEnd();
}
HttpContext.Response
// using Microsoft.AspNetCore.Http;
httpContext.Response.StatusCode = StatusCodes.Status200OK;
// using Microsoft.Net.Http.Headers;
var mediaType = new MediaTypeHeaderValue("application/json");
mediaType.Encoding = System.Text.Encoding.UTF8;
httpContext.Response.ContentType = mediaType.ToString();
httpContext.Response.ContentType = "text/html";
string responseContent = GetResponseContent();
await httpContext.Response.WriteAsync(responseContent);
??发送响应标头非常复杂,这一事实,如果任何内容都已写入响应正文将它们设置,它们将不发送。
??解决方案是将设置将右之前调用写入响应启动的回调方法。 最好的做法是在开始 Invoke 中间件中的方法。 这是此回调方法,设置响应标头。
??下面的代码设置调用的回调方法 SetHeaders :public async Task Invoke(HttpContext httpContext)
{
// ...
httpContext.Response.OnStarting(SetHeaders, state: httpContext);
}
// using Microsoft.AspNet.Http.Headers;
// using Microsoft.Net.Http.Headers;
private Task SetHeaders(object context)
{
var httpContext = (HttpContext)context;
// Set header with single value
httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
// Set header with multiple values
string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
// Translating ASP.NET 4‘s HttpContext.Response.RedirectLocation
httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
// Or
httpContext.Response.Redirect("http://www.example.com");
// GetTypedHeaders extension method provides strongly typed access to many headers
var responseHeaders = httpContext.Response.GetTypedHeaders();
// Translating ASP.NET 4‘s HttpContext.Response.CacheControl
responseHeaders.CacheControl = new CacheControlHeaderValue
{
MaxAge = new System.TimeSpan(365, 0, 0, 0)
// Many more properties available
};
// If you use .Net 4.6+, Task.CompletedTask will be a bit faster
return Task.FromResult(0);
}
??发送 cookie 需要用于发送响应标头以使用相同的回调:public async Task Invoke(HttpContext httpContext)
{
// ...
httpContext.Response.OnStarting(SetCookies, state: httpContext);
httpContext.Response.OnStarting(SetHeaders, state: httpContext);
}
private Task SetCookies(object context)
{
var httpContext = (HttpContext)context;
IResponseCookies responseCookies = httpContext.Response.Cookies;
responseCookies.Append("cookie1name", "cookie1value");
responseCookies.Append("cookie2name", "cookie2value",
new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
// If you use .Net 4.6+, Task.CompletedTask will be a bit faster
return Task.FromResult(0);
}
文章标题:ASP.NET Core 2.0中的HttpContext
文章链接:http://soscw.com/index.php/essay/57723.html