【转】ASP.NET Core 2.0中的HttpContext
2021-04-22 13:30
标签:except sharp cat 响应 https string known 启动 iss 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 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 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 回调方法将如下所示: 转自:https://www.jianshu.com/p/30796ccc6fcb 【转】ASP.NET Core 2.0中的HttpContext 标签:except sharp cat 响应 https string known 启动 iss 原文地址:https://www.cnblogs.com/hycms/p/12243527.htmlHttpContext
IDictionary
string requestId = httpContext.TraceIdentifier;
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")
IList
// 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 ""
IList
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();
}
// 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/essay/78100.html