ASP.NET Core 2.0中的HttpContext相較於ASP.NET Framework有一些變化,這邊列出一些之間的區別。html
在ASP.NET Framework中的 System.Web.HttpContext 對應 ASP.NET Core 2.0中的 Microsoft.AspNetCore.Http.HttpContext。json
HttpContext.Items轉換成:cookie
IDictionary<object, object> items = httpContext.Items;
請求的惟一的ID:app
string requestId = httpContext.TraceIdentifier;
HttpContext.Requestasync
HttpContext.Request.HttpMethod 轉換成:ide
string httpMethod = httpContext.Request.Method;
HttpContext.Request.QueryString 轉換成:url
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 轉換成:code
// using Microsoft.AspNetCore.Http.Extensions; var url = httpContext.Request.GetDisplayUrl();
HttpContext.Request.IsSecureConnection 轉換成:orm
var isSecureConnection = httpContext.Request.IsHttps;
HttpContext.Request.UserHostAddress 轉換成:htm
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); }
轉自:https://www.jianshu.com/p/30796ccc6fcb