首页>教程>.NET Core>将 HTTP 处理程序和模块迁移到 ASP.NET Core 中间件

此组别内的文章

需要支持?

如果通过文档没办法解决您的问题,请提交工单获取我们的支持!

将 HTTP 处理程序和模块迁移到 ASP.NET Core 中间件

内容纲要

本文演示如何将现有 ASP.NET HTTP 模块和处理程序从 system.webserver 迁移到 ASP.NET Core 中间件

重新访问的模块和处理程序

在继续讨论 ASP.NET Core 中间件之前,让我们先回顾一下 HTTP 模块和处理程序如何工作:

处理程序是:

  • 实现 IHttpHandler 的类
  • 用于处理具有给定文件名或扩展名(如 .report)的请求
  • 在 Web.config 中进行配置

模块是:

  • 实现 IHttpModule 的类
  • 对每个请求进行调用
  • 能够短路(停止请求的进一步处理)
  • 能够添加到 HTTP 响应,或创建自己的响应
  • 在 Web.config 中进行配置

模块处理传入请求的顺序取决于:

  1. 由 ASP.NET 触发的序列事件,如 BeginRequest 和 AuthenticateRequest。 有关完整列表,请参见System.Web.HttpApplication。 每个模块都可以为一个或多个事件创建处理程序。
  2. 它们在 Web.config 中进行配置的顺序(对于同一事件)。

除了模块之外,可以将生命周期事件的处理程序添加到 Global.asax.cs 文件。 这些处理程序在所配置的模块中的处理程序之后运行。

从处理程序和模块到中间件

中间件比 HTTP 模块和处理程序更简单:

  • 模块、处理程序、Global.asax.cs、Web.config(IIS 配置除外)和应用程序生命周期都不存在
  • 模块和处理程序的角色由中间件接管
  • 中间件使用代码而不是在 Web.config 中进行配置
  • 管道分支使你可以不仅基于 URL,而且基于请求标头、查询字符串等向特定中间件发送请求。

中间件与模块非常相似:

中间件和模块采用不同顺序进行处理:

在上图中,请注意身份验证中间件如何使请求短路。

将模块代码迁移到中间件

现有 HTTP 模块类似于下面这样:C#复制

  1. // ASP.NET 4 module
  2. using System;
  3. using System.Web;
  4. namespace MyApp.Modules
  5. {
  6. public class MyModule : IHttpModule
  7. {
  8. public void Dispose()
  9. {
  10. }
  11. public void Init(HttpApplication application)
  12. {
  13. application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
  14. application.EndRequest += (new EventHandler(this.Application_EndRequest));
  15. }
  16. private void Application_BeginRequest(Object source, EventArgs e)
  17. {
  18. HttpContext context = ((HttpApplication)source).Context;
  19. // Do something with context near the beginning of request processing.
  20. }
  21. private void Application_EndRequest(Object source, EventArgs e)
  22. {
  23. HttpContext context = ((HttpApplication)source).Context;
  24. // Do something with context near the end of request processing.
  25. }
  26. }
  27. }

中间件页面中所示,ASP.NET Core 中间件是一个类,它会公开采用 HttpContext 并返回 Task 的 方法。 新中间件类似于下面这样:C#复制

  1. // ASP.NET Core middleware
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Http;
  4. using System.Threading.Tasks;
  5. namespace MyApp.Middleware
  6. {
  7. public class MyMiddleware
  8. {
  9. private readonly RequestDelegate _next;
  10. public MyMiddleware(RequestDelegate next)
  11. {
  12. _next = next;
  13. }
  14. public async Task Invoke(HttpContext context)
  15. {
  16. // Do something with context near the beginning of request processing.
  17. await _next.Invoke(context);
  18. // Clean up.
  19. }
  20. }
  21. public static class MyMiddlewareExtensions
  22. {
  23. public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
  24. {
  25. return builder.UseMiddleware<MyMiddleware>();
  26. }
  27. }
  28. }

上面的中间件模板取自有关编写中间件的部分。

通过 MyMiddlewareExtensions 帮助程序类可以更轻松地在 类中配置中间件。 UseMyMiddleware 方法会将中间件类添加到请求管道。 中间件所需的服务会注入中间件的构造函数中。

模块可能会终止请求,例如如果用户未获得授权:C#复制

  1. // ASP.NET 4 module that may terminate the request
  2. private void Application_BeginRequest(Object source, EventArgs e)
  3. {
  4. HttpContext context = ((HttpApplication)source).Context;
  5. // Do something with context near the beginning of request processing.
  6. if (TerminateRequest())
  7. {
  8. context.Response.End();
  9. return;
  10. }
  11. }

中间件通过不对管道中的下一个中间件调用 Invoke 来处理此问题。 请记住,这不会完全终止请求,因为在响应通过管道返回时,仍会调用以前的中间件。C#复制

  1. // ASP.NET Core middleware that may terminate the request
  2. public async Task Invoke(HttpContext context)
  3. {
  4. // Do something with context near the beginning of request processing.
  5. if (!TerminateRequest())
  6. await _next.Invoke(context);
  7. // Clean up.
  8. }

将模块的功能迁移到新中间件时,你可能会发现代码未编译,因为 HttpContext 类在 ASP.NET Core 中进行了重大更改。 稍后,你将了解如何迁移到新的 ASP.NET Core HttpContext。

将模块插入迁移到请求管道中

HTTP 模块通常使用 Web.config 添加到请求管道:XML复制

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!--ASP.NET 4 web.config-->
  3. <configuration>
  4. <system.webServer>
  5. <modules>
  6. <add name="MyModule" type="MyApp.Modules.MyModule"/>
  7. </modules>
  8. </system.webServer>
  9. </configuration>

对此进行转换的方法是在 类中将新中间件添加到请求管道:C#复制

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  2. {
  3. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  4. loggerFactory.AddDebug();
  5. if (env.IsDevelopment())
  6. {
  7. app.UseDeveloperExceptionPage();
  8. app.UseBrowserLink();
  9. }
  10. else
  11. {
  12. app.UseExceptionHandler("/Home/Error");
  13. }
  14. app.UseMyMiddleware();
  15. app.UseMyMiddlewareWithParams();
  16. var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
  17. var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
  18. app.UseMyMiddlewareWithParams(myMiddlewareOptions);
  19. app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
  20. app.UseMyTerminatingMiddleware();
  21. // Create branch to the MyHandlerMiddleware.
  22. // All requests ending in .report will follow this branch.
  23. app.MapWhen(
  24. context => context.Request.Path.ToString().EndsWith(".report"),
  25. appBranch => {
  26. // ... optionally add more middleware to this branch
  27. appBranch.UseMyHandler();
  28. });
  29. app.MapWhen(
  30. context => context.Request.Path.ToString().EndsWith(".context"),
  31. appBranch => {
  32. appBranch.UseHttpContextDemoMiddleware();
  33. });
  34. app.UseStaticFiles();
  35. app.UseMvc(routes =>
  36. {
  37. routes.MapRoute(
  38. name: "default",
  39. template: "{controller=Home}/{action=Index}/{id?}");
  40. });
  41. }

在管道中插入新中间件的确切位置取决于它作为模块处理的事件(BeginRequestEndRequest 等) 及其在 Web.config 的模块列表中的顺序。

如前所述,在 ASP.NET Core 中没有应用程序生命周期,中间件处理响应的顺序与模块使用的顺序不同。 这可能会使排序决策更具挑战性。

如果排序成为问题,可以将模块拆分为多个可以独立排序的中间件组件。

将处理程序代码迁移到中间件

HTTP 处理程序类似于下面这样:C#复制

  1. // ASP.NET 4 handler
  2. using System.Web;
  3. namespace MyApp.HttpHandlers
  4. {
  5. public class MyHandler : IHttpHandler
  6. {
  7. public bool IsReusable { get { return true; } }
  8. public void ProcessRequest(HttpContext context)
  9. {
  10. string response = GenerateResponse(context);
  11. context.Response.ContentType = GetContentType();
  12. context.Response.Output.Write(response);
  13. }
  14. // ...
  15. private string GenerateResponse(HttpContext context)
  16. {
  17. string title = context.Request.QueryString["title"];
  18. return string.Format("Title of the report: {0}", title);
  19. }
  20. private string GetContentType()
  21. {
  22. return "text/plain";
  23. }
  24. }
  25. }

在 ASP.NET Core 项目中,可将此转换为类似于下面这样的中间件:C#复制

  1. // ASP.NET Core middleware migrated from a handler
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Http;
  4. using System.Threading.Tasks;
  5. namespace MyApp.Middleware
  6. {
  7. public class MyHandlerMiddleware
  8. {
  9. // Must have constructor with this signature, otherwise exception at run time
  10. public MyHandlerMiddleware(RequestDelegate next)
  11. {
  12. // This is an HTTP Handler, so no need to store next
  13. }
  14. public async Task Invoke(HttpContext context)
  15. {
  16. string response = GenerateResponse(context);
  17. context.Response.ContentType = GetContentType();
  18. await context.Response.WriteAsync(response);
  19. }
  20. // ...
  21. private string GenerateResponse(HttpContext context)
  22. {
  23. string title = context.Request.Query["title"];
  24. return string.Format("Title of the report: {0}", title);
  25. }
  26. private string GetContentType()
  27. {
  28. return "text/plain";
  29. }
  30. }
  31. public static class MyHandlerExtensions
  32. {
  33. public static IApplicationBuilder UseMyHandler(this IApplicationBuilder builder)
  34. {
  35. return builder.UseMiddleware<MyHandlerMiddleware>();
  36. }
  37. }
  38. }

此中间件与对应于模块的中间件非常相似。 唯一的真正区别是此处没有调用 _next.Invoke(context)。 这十分重要,因为处理程序位于请求管道末尾,因此没有下一个中间件要进行调用。

将处理程序插入迁移到请求管道中

HTTP 处理程序的配置在 Web.config 中进行,类似于下面这样:XML复制

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!--ASP.NET 4 web.config-->
  3. <configuration>
  4. <system.webServer>
  5. <handlers>
  6. <add name="MyHandler" verb="*" path="*.report" type="MyApp.HttpHandlers.MyHandler" resourceType="Unspecified" preCondition="integratedMode"/>
  7. </handlers>
  8. </system.webServer>
  9. </configuration>

可以通过在 Startup 类中将新处理程序中间件添加到请求管道来对此进行转换,类似于从模块转换的中间件。 该方法的问题在于,它会将所有请求都发送到新处理程序中间件。 但是,你仅希望具有给定扩展名的请求到达中间件。 这会提供与 HTTP 处理程序相同的功能。

一种解决方案是使用 MapWhen 扩展方法为具有给定扩展名的请求对管道进行分支。 在添加其他中间件的相同 Configure 方法中执行此操作:C#复制

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  2. {
  3. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  4. loggerFactory.AddDebug();
  5. if (env.IsDevelopment())
  6. {
  7. app.UseDeveloperExceptionPage();
  8. app.UseBrowserLink();
  9. }
  10. else
  11. {
  12. app.UseExceptionHandler("/Home/Error");
  13. }
  14. app.UseMyMiddleware();
  15. app.UseMyMiddlewareWithParams();
  16. var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
  17. var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
  18. app.UseMyMiddlewareWithParams(myMiddlewareOptions);
  19. app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
  20. app.UseMyTerminatingMiddleware();
  21. // Create branch to the MyHandlerMiddleware.
  22. // All requests ending in .report will follow this branch.
  23. app.MapWhen(
  24. context => context.Request.Path.ToString().EndsWith(".report"),
  25. appBranch => {
  26. // ... optionally add more middleware to this branch
  27. appBranch.UseMyHandler();
  28. });
  29. app.MapWhen(
  30. context => context.Request.Path.ToString().EndsWith(".context"),
  31. appBranch => {
  32. appBranch.UseHttpContextDemoMiddleware();
  33. });
  34. app.UseStaticFiles();
  35. app.UseMvc(routes =>
  36. {
  37. routes.MapRoute(
  38. name: "default",
  39. template: "{controller=Home}/{action=Index}/{id?}");
  40. });
  41. }

MapWhen 采用以下参数:

  1. 一个 lambda,它采用 HttpContext,并在请求应沿着分支向下前进时返回 true。 这意味着不仅可以基于请求扩展名,还可以基于请求标头、查询字符串参数等对请求进行分支。
  2. 一个 lambda,它采用 IApplicationBuilder 并为分支添加所有中间件。 这意味着可以将其他中间件添加到处理程序中间件前面的分支。

中间件在对所有请求调用分支之前添加到管道;分支对它们没有影响。

使用选项模式加载中间件选项

某些模块和处理程序具有存储在 Web.config 中的配置选项。但是在 ASP.NET Core 中,使用新配置模型取代了 Web.config。

配置系统提供了以下选项来解决此问题:

  • 创建用于保存中间件选项的类,例如:C#复制public class MyMiddlewareOptions { public string Param1 { get; set; } public string Param2 { get; set; } }
  • 存储选项值配置系统允许将选项值存储在所需的任何位置。 但是,大多数站点使用 appsettings.json,因此我们会采用该方法:JSON复制{ "MyMiddlewareOptionsSection": { "Param1": "Param1Value", "Param2": "Param2Value" } } 此处的 MyMiddlewareOptionsSection 是节名称。 它不必与选项类的名称相同。
  • 将选项值与选项类关联选项模式使用 ASP.NET Core 的依赖项注入框架将选项类型(例如 MyMiddlewareOptions)与具有实际选项的 MyMiddlewareOptions 对象关联。更新 Startup 类:
    • 如果使用 appsettings.json,请将它添加到 Startup 构造函数中的配置生成器:
  1. public Startup(IHostingEnvironment env)
  2. {
  3. var builder = new ConfigurationBuilder()
  4. .SetBasePath(env.ContentRootPath)
  5. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  6. .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
  7. .AddEnvironmentVariables();
  8. Configuration = builder.Build();
  9. }
  • 配置选项服务:
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // Setup options service
  4. services.AddOptions();
  5. // Load options from section "MyMiddlewareOptionsSection"
  6. services.Configure<MyMiddlewareOptions>(
  7. Configuration.GetSection("MyMiddlewareOptionsSection"));
  8. // Add framework services.
  9. services.AddMvc();
  10. }
  • 将选项与选项类关联:
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // Setup options service
  4. services.AddOptions();
  5. // Load options from section "MyMiddlewareOptionsSection"
  6. services.Configure<MyMiddlewareOptions>(
  7. Configuration.GetSection("MyMiddlewareOptionsSection"));
  8. // Add framework services.
  9. services.AddMvc();
  10. }
  • 将选项注入中间件构造函数。 这类似于将选项注入控制器。
  1. public class MyMiddlewareWithParams
  2. {
  3. private readonly RequestDelegate _next;
  4. private readonly MyMiddlewareOptions _myMiddlewareOptions;
  5. public MyMiddlewareWithParams(RequestDelegate next,
  6. IOptions<MyMiddlewareOptions> optionsAccessor)
  7. {
  8. _next = next;
  9. _myMiddlewareOptions = optionsAccessor.Value;
  10. }
  11. public async Task Invoke(HttpContext context)
  12. {
  13. // Do something with context near the beginning of request processing
  14. // using configuration in _myMiddlewareOptions
  15. await _next.Invoke(context);
  16. // Do something with context near the end of request processing
  17. // using configuration in _myMiddlewareOptions
  18. }
  19. }
  • 将中间件添加到 的 UseMiddleware 扩展方法负责依赖项注入。这并不限于 IOptions 对象。 中间件所需的任何其他对象都可以通过这种方式注入。

通过直接注入加载中间件选项

选项模式的优点在于,它可在选项值与其使用者之间创建松散耦合。 将选项类与实际选项值相关联后,任何其他类都可以通过依赖项注入框架访问选项。 无需围绕选项值进行传递。

不过如果要通过不同选项使用两次相同中间件,则这会出现问题。 例如,在允许不同角色的不同分支中使用的授权中间件。 无法将两个不同选项对象与一个选项类关联。

解决方案是在 Startup 类中获取具有实际选项值的选项对象,并将这些内容直接传递给中间件的每个实例。

  • 将第二个键添加到 appsettings.json若要将第二组选项添加到 appsettings.json 文件,请使用新键来唯一地标识它:
  1. {
  2. "MyMiddlewareOptionsSection2": {
  3. "Param1": "Param1Value2",
  4. "Param2": "Param2Value2"
  5. },
  6. "MyMiddlewareOptionsSection": {
  7. "Param1": "Param1Value",
  8. "Param2": "Param2Value"
  9. }
  10. }
  • 检索选项值并将它们传递给中间件。 Use... 扩展方法(用于将中间件添加到管道)是要传入选项值的逻辑位置:
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  2. {
  3. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  4. loggerFactory.AddDebug();
  5. if (env.IsDevelopment())
  6. {
  7. app.UseDeveloperExceptionPage();
  8. app.UseBrowserLink();
  9. }
  10. else
  11. {
  12. app.UseExceptionHandler("/Home/Error");
  13. }
  14. app.UseMyMiddleware();
  15. app.UseMyMiddlewareWithParams();
  16. var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
  17. var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
  18. app.UseMyMiddlewareWithParams(myMiddlewareOptions);
  19. app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
  20. app.UseMyTerminatingMiddleware();
  21. // Create branch to the MyHandlerMiddleware.
  22. // All requests ending in .report will follow this branch.
  23. app.MapWhen(
  24. context => context.Request.Path.ToString().EndsWith(".report"),
  25. appBranch => {
  26. // ... optionally add more middleware to this branch
  27. appBranch.UseMyHandler();
  28. });
  29. app.MapWhen(
  30. context => context.Request.Path.ToString().EndsWith(".context"),
  31. appBranch => {
  32. appBranch.UseHttpContextDemoMiddleware();
  33. });
  34. app.UseStaticFiles();
  35. app.UseMvc(routes =>
  36. {
  37. routes.MapRoute(
  38. name: "default",
  39. template: "{controller=Home}/{action=Index}/{id?}");
  40. });
  41. }
  • 使中间件可以采用选项参数。 提供 Use... 扩展方法(它采用选项参数并将它传递给 UseMiddleware)的重载。 使用参数调用 UseMiddleware 时,它会在实例化中间件对象时将参数传递给中间件构造函数。
  1. public static class MyMiddlewareWithParamsExtensions
  2. {
  3. public static IApplicationBuilder UseMyMiddlewareWithParams(
  4. this IApplicationBuilder builder)
  5. {
  6. return builder.UseMiddleware<MyMiddlewareWithParams>();
  7. }
  8. public static IApplicationBuilder UseMyMiddlewareWithParams(
  9. this IApplicationBuilder builder, MyMiddlewareOptions myMiddlewareOptions)
  10. {
  11. return builder.UseMiddleware<MyMiddlewareWithParams>(
  12. new OptionsWrapper<MyMiddlewareOptions>(myMiddlewareOptions));
  13. }
  14. }
  • 请注意这如何在 OptionsWrapper 对象中包装选项对象。 这会实现中间件构造函数所需的 IOptions

迁移到新 HttpContext

你在前面曾看到,中间件中的 Invoke 方法采用类型为 HttpContext 的参数:

  1. public async Task Invoke(HttpContext context)

HttpContext 在 ASP.NET Core 中进行了重大更改。 此部分演示如何将 System.Web.HttpContext 最常用的属性转换为新 

HttpContext

HttpContext.Items 转换为:

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

唯一请求 ID(无 System.Web.HttpContext 对应项)

提供每个请求的唯一 id。 包含在日志中会非常有用。

  1. string requestId = httpContext.TraceIdentifier;

HttpContext.Request

HttpContext.Request.HttpMethod 转换为:

  1. string httpMethod = httpContext.Request.Method;

HttpContext.Request.QueryString 转换为:

  1. IQueryCollection queryParameters = httpContext.Request.Query;
  2. // If no query parameter "key" used, values will have 0 items
  3. // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  4. // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  5. IList<string> values = queryParameters["key"];
  6. // If no query parameter "key" used, value will be ""
  7. // If single value used for a key (...?key=v1), value will be "v1"
  8. // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  9. string value = queryParameters["key"].ToString();

HttpContext.Request.Url 和 HttpContext.Request.RawUrl 转换为:

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

HttpContext.Request.IsSecureConnection 转换为:

  1. var isSecureConnection = httpContext.Request.IsHttps;

HttpContext.Request.UserHostAddress 转换为:

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

HttpContext.Request. 转换为:

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

HttpContext.Request.RequestContext.RouteData 转换为:

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

HttpContext.Request.Headers 转换为:

  1. // using Microsoft.AspNetCore.Http.Headers;
  2. // using Microsoft.Net.Http.Headers;
  3. IHeaderDictionary headersDictionary = httpContext.Request.Headers;
  4. // GetTypedHeaders extension method provides strongly typed access to many headers
  5. var requestHeaders = httpContext.Request.GetTypedHeaders();
  6. CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
  7. // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
  8. IList<string> unknownheaderValues = headersDictionary["unknownheader"];
  9. string unknownheaderValue = headersDictionary["unknownheader"].ToString();
  10. // For known header, knownheaderValues has 1 item and knownheaderValue is the value
  11. IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
  12. string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();

HttpContext.Request.UserAgent 转换为:

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

HttpContext.Request.UrlReferrer 转换为:

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

HttpContext.Request.ContentType 转换为:

  1. // using Microsoft.Net.Http.Headers;
  2. MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
  3. string contentType = mediaHeaderValue?.MediaType.ToString(); // ex. application/x-www-form-urlencoded
  4. string contentMainType = mediaHeaderValue?.Type.ToString(); // ex. application
  5. string contentSubType = mediaHeaderValue?.SubType.ToString(); // ex. x-www-form-urlencoded
  6. System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;

HttpContext.Request.Form 转换为:

  1. if (httpContext.Request.HasFormContentType)
  2. {
  3. IFormCollection form;
  4. form = httpContext.Request.Form; // sync
  5. // Or
  6. form = await httpContext.Request.ReadFormAsync(); // async
  7. string firstName = form["firstname"];
  8. string lastName = form["lastname"];
  9. }

 警告

仅当内容子类型为 x-www-form-urlencoded 或 form-data 时才读取窗体值。

HttpContext.Request.InputStream 转换为:

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

 警告

仅在管道末尾的处理程序类型中间件中才使用此代码。

对于每个请求,只能读取上面所示的原始正文一次。 在首次读取之后尝试读取正文的中间件会读取空正文。

这不适用于读取前面所示的窗体,因为该操作在缓冲区中完成。

HttpContext.Response

HttpContext.Response.Status 和 HttpContext.Response.StatusDescription 转换为:

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

HttpContext.Response.ContentEncoding 和 HttpContext.Response.ContentType 转换为:

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

HttpContext.Response.ContentType 自己也转换为:

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

HttpContext.Response.Output 转换为:

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

HttpContext.Response.TransmitFile

ASP.NET Core 中的请求功能中讨论了如何提供文件。

HttpContext.Response.Headers

发送响应头比较复杂,因为如果在将任何内容写入响应正文后设置它们,则不会进行发送。

解决方案是设置恰好在开始向响应写入之前调用的回调方法。 最好在中间件中的 Invoke 方法开头执行此操作。 由此回调方法设置响应头。

下面的代码设置名为 SetHeaders 的回调方法:

  1. public async Task Invoke(HttpContext httpContext)
  2. {
  3. // ...
  4. httpContext.Response.OnStarting(SetHeaders, state: httpContext);

SetHeaders 回调方法会类似于下面这样:

  1. // using Microsoft.AspNet.Http.Headers;
  2. // using Microsoft.Net.Http.Headers;
  3. private Task SetHeaders(object context)
  4. {
  5. var httpContext = (HttpContext)context;
  6. // Set header with single value
  7. httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
  8. // Set header with multiple values
  9. string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
  10. httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
  11. // Translating ASP.NET 4's HttpContext.Response.RedirectLocation
  12. httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
  13. // Or
  14. httpContext.Response.Redirect("http://www.example.com");
  15. // GetTypedHeaders extension method provides strongly typed access to many headers
  16. var responseHeaders = httpContext.Response.GetTypedHeaders();
  17. // Translating ASP.NET 4's HttpContext.Response.CacheControl
  18. responseHeaders.CacheControl = new CacheControlHeaderValue
  19. {
  20. MaxAge = new System.TimeSpan(365, 0, 0, 0)
  21. // Many more properties available
  22. };
  23. // If you use .NET Framework 4.6+, Task.CompletedTask will be a bit faster
  24. return Task.FromResult(0);
  25. }

HttpContext.Response.s

Cookie 在 Cookie 响应头中传递给浏览器。 因此,发送 cookie 需要与用于发送响应头相同的回调:

  1. public async Task Invoke(HttpContext httpContext)
  2. {
  3. // ...
  4. httpContext.Response.OnStarting(SetCookies, state: httpContext);
  5. httpContext.Response.OnStarting(SetHeaders, state: httpContext);

SetCookies 回调方法会类似于下面这样:

  1. private Task SetCookies(object context)
  2. {
  3. var httpContext = (HttpContext)context;
  4. IResponseCookies responseCookies = httpContext.Response.Cookies;
  5. responseCookies.Append("cookie1name", "cookie1value");
  6. responseCookies.Append("cookie2name", "cookie2value",
  7. new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
  8. // If you use .NET Framework 4.6+, Task.CompletedTask will be a bit faster
  9. return Task.FromResult(0);
  10. }
0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
今日签到
私信列表
搜索