ASP.NET Core 2.0中的HttpContext

原文: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);
}

相关推荐