码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET Core 2.0中的HttpContext

时间:2020-05-20 14:40:25      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:tpm   rop   headers   color   display   cookie   header   自身   redirect   

原文:ASP.NET Core 2.0中的HttpContext

说明:参考微软官方文档。

??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

??HttpContext.Items转换成:

    IDictionary<object, object> items = httpContext.Items;

??请求的唯一的ID:

string requestId = httpContext.TraceIdentifier;

HttpContext.Request

??HttpContext.Request.HttpMethod 转换成:

string httpMethod = httpContext.Request.Method;

??HttpContext.Request.QueryString 转换成:

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

??HttpContext.Request.Url 和 HttpContext.Request.RawUrl 转换成:

// using Microsoft.AspNetCore.Http.Extensions;
var url = httpContext.Request.GetDisplayUrl();

??HttpContext.Request.IsSecureConnection 转换成:

var isSecureConnection = httpContext.Request.IsHttps;

??HttpContext.Request.UserHostAddress 转换成:

var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();

??HttpContext.Request.Cookies 转换成:

IRequestCookieCollection cookies = httpContext.Request.Cookies;
string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
string knownCookieValue = cookies["cookie1name"]; // will be actual value

??HttpContext.Request.RequestContext.RouteData 转换成:

var routeValue = httpContext.GetRouteValue("key");

??HttpContext.Request.Headers 转换成:

// 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> unknownheaderValues = headersDictionary["unknownheader"];
string unknownheaderValue = headersDictionary["unknownheader"].ToString();
// For known header, knownheaderValues has 1 item and knownheaderValue is the value
IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();

??HttpContext.Request.UserAgent 转换成:

string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();

??HttpContext.Request.UrlReferrer 转换成:

string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();

??HttpContext.Request.ContentType 转换成:

// 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;

??HttpContext.Request.Form转换成:

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"];
}

??HttpContext.Request.InputStream 转换成:

string inputBody;
using (var reader = new System.IO.StreamReader(
httpContext.Request.Body, System.Text.Encoding.UTF8))
{
inputBody = reader.ReadToEnd();
}

HttpContext.Response

??HttpContext.Response.Status 和 HttpContext.Response.StatusDescription转换成:

// using Microsoft.AspNetCore.Http;
httpContext.Response.StatusCode = StatusCodes.Status200OK;

??HttpContext.Response.ContentEncoding 和 HttpContext.Response.ContentType 转换成:

// 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 上其自身还转换成:

httpContext.Response.ContentType = "text/html";

??HttpContext.Response.Output 转换成:

string responseContent = GetResponseContent();
await httpContext.Response.WriteAsync(responseContent);

HttpContext.Response.Headers
??发送响应标头非常复杂,这一事实,如果任何内容都已写入响应正文将它们设置,它们将不发送。
??解决方案是将设置将右之前调用写入响应启动的回调方法。 最好的做法是在开始 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);
}

HttpContext.Response.Cookies
??发送 cookie 需要用于发送响应标头以使用相同的回调:

public async Task Invoke(HttpContext httpContext)
{
    // ...
    httpContext.Response.OnStarting(SetCookies, state: httpContext);
    httpContext.Response.OnStarting(SetHeaders, state: httpContext);
}

??SetCookies 回调方法将如下所示:

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

标签:tpm   rop   headers   color   display   cookie   header   自身   redirect   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12923012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!