[Turn] HttpContext in ASP.NET Core 2.0

  ASP.NET Core 2.0 HttpContext in ASP.NET Framework compared to some changes, some of the differences between listed here.

  System.Web.HttpContext in ASP.NET Framework corresponding ASP.NET Core 2.0 is Microsoft.AspNetCore.Http.HttpContext.

HttpContext

  HttpContext.Items converted into:

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

  Unique ID of the request:

string requestId = httpContext.TraceIdentifier;

 HttpContext.Request

  HttpContext.Request.HttpMethod converted into:

string httpMethod = httpContext.Request.Method;

   HttpContext.Request.QueryString converted into:

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 and HttpContext.Request.RawUrl converted into:

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

   HttpContext.Request.IsSecureConnection converted into:

var isSecureConnection = httpContext.Request.IsHttps;

   HttpContext.Request.UserHostAddress converted into:

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

   HttpContext.Request.Cookies converted into:

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 converted into:

// 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 converted into:

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

   HttpContext.Request.UrlReferrer converted into:

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

  HttpContext.Request.ContentType converted into:

// 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 converted into:

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 converted into:

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

 HttpContext.Response

  HttpContext.Response.Status and HttpContext.Response.StatusDescription converted into:

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

   HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType converted into:

// using Microsoft.Net.Http.Headers;
var mediaType = new MediaTypeHeaderValue("application/json");
mediaType.Encoding = System.Text.Encoding.UTF8;
httpContext.Response.ContentType = mediaType.ToString();

   On HttpContext.Response.ContentType itself further converted to:

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

  HttpContext.Response.Output converted into:

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

 HttpContext.Response.Headers
  send response headers are very complicated, the fact that, if anything has been written in response to the body to set them, they will not be sent.
  The solution is to set a callback method respond to the start of the call written before the right. The best approach is to start Invoke method in middleware. This is the callback method, set the response headers.
  The following code sets called callback method 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
  transmission for transmitting the cookie response header need to use the same callback:

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

   SetCookies callback method is as follows:

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);
}

 Transfer: https: //www.jianshu.com/p/30796ccc6fcb

Guess you like

Origin www.cnblogs.com/hycms/p/12243527.html