ASP.NET Core 中间件ASP.NET Core Middleware

作者:Rick AndersonSteve SmithBy Rick Anderson and Steve Smith

中间件是一种装配到应用管道以处理请求和响应的软件。Middleware is software that's assembled into an app pipeline to handle requests and responses. 每个组件:Each component:

  • 选择是否将请求传递到管道中的下一个组件。Chooses whether to pass the request to the next component in the pipeline.
  • 可在管道中的下一个组件前后执行工作。Can perform work before and after the next component in the pipeline.

请求委托用于生成请求管道。Request delegates are used to build the request pipeline. 请求委托处理每个 HTTP 请求。The request delegates handle each HTTP request.

使用 RunMapUse 扩展方法来配置请求委托。Request delegates are configured using Run, Map, and Use extension methods. 可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在可重用的类中对其进行定义。An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. 这些可重用的类和并行匿名方法即为中间件 ,也叫中间件组件 。These reusable classes and in-line anonymous methods are middleware, also called middleware components. 请求管道中的每个中间件组件负责调用管道中的下一个组件,或使管道短路。Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. 当中间件短路时,它被称为“终端中间件” ,因为它阻止中间件进一步处理请求。When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware from processing the request.

将 HTTP 处理程序和模块迁移到 ASP.NET Core 中间件介绍了 ASP.NET Core 和 ASP.NET 4.x 中请求管道之间的差异,并提供了更多的中间件示例。将 HTTP 处理程序和模块迁移到 ASP.NET Core 中间件 explains the difference between request pipelines in ASP.NET Core and ASP.NET 4.x and provides additional middleware samples.

使用 IApplicationBuilder 创建中间件管道Create a middleware pipeline with IApplicationBuilder

ASP.NET Core 请求管道包含一系列请求委托,依次调用。The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. 下图演示了这一概念。The following diagram demonstrates the concept. 沿黑色箭头执行。The thread of execution follows the black arrows.

请求处理模式显示请求到达、通过三个中间件进行处理以及响应离开应用。

每个委托均可在下一个委托前后执行操作。Each delegate can perform operations before and after the next delegate. 应尽早在管道中调用异常处理委托,这样它们就能捕获在管道的后期阶段发生的异常。Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.

尽可能简单的 ASP.NET Core 应用设置了处理所有请求的单个请求委托。The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. 这种情况不包括实际请求管道。This case doesn't include an actual request pipeline. 调用单个匿名函数以响应每个 HTTP 请求。Instead, a single anonymous function is called in response to every HTTP request.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello, World!");
        });
    }
}

第一个 Run 委托终止了管道。The first Run delegate terminates the pipeline.

Use 将多个请求委托链接在一起。Chain multiple request delegates together with Use. next 参数表示管道中的下一个委托。The next parameter represents the next delegate in the pipeline. 可通过不 调用 next 参数使管道短路。You can short-circuit the pipeline by not calling the next parameter. 通常可在下一个委托前后执行操作,如以下示例所示:You can typically perform actions both before and after the next delegate, as the following example demonstrates:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            // Do work that doesn't write to the Response.
            await next.Invoke();
            // Do logging or other work that doesn't write to the Response.
        });

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from 2nd delegate.");
        });
    }
}

当委托不将请求传递给下一个委托时,它被称为“让请求管道短路” 。When a delegate doesn't pass a request to the next delegate, it's called short-circuiting the request pipeline. 通常需要短路,因为这样可以避免不必要的工作。Short-circuiting is often desirable because it avoids unnecessary work. 例如,静态文件中间件可以处理对静态文件的请求,并让管道的其余部分短路,从而起到终端中间件 的作用。For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. 如果中间件添加到管道中,且位于终止进一步处理的中间件前,它们仍处理 next.Invoke 语句后面的代码。Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke statements. 不过,请参阅下面有关尝试对已发送的响应执行写入操作的警告。However, see the following warning about attempting to write to a response that has already been sent.

警告

在向客户端发送响应后,请勿调用 next.InvokeDon't call next.Invoke after the response has been sent to the client. 响应启动后,针对 HttpResponse 的更改将引发异常。Changes to HttpResponse after the response has started throw an exception. 例如,设置标头和状态代码更改将引发异常。For example, changes such as setting headers and a status code throw an exception. 调用 next 后写入响应正文:Writing to the response body after calling next:

  • 可能导致违反协议。May cause a protocol violation. 例如,写入的长度超过规定的 Content-LengthFor example, writing more than the stated Content-Length.
  • 可能损坏正文格式。May corrupt the body format. 例如,向 CSS 文件中写入 HTML 页脚。For example, writing an HTML footer to a CSS file.

HasStarted 是一个有用的提示,指示是否已发送标头或已写入正文。HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.

中间件顺序Middleware order

Startup.Configure 方法添加中间件组件的顺序定义了针对请求调用这些组件的顺序,以及响应的相反顺序。The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. 此顺序对于安全性、性能和功能至关重要。 The order is critical for security, performance, and functionality.

下面的 Startup.Configure 方法按照建议的顺序增加与安全相关的中间件组件:The following Startup.Configure method adds security related middleware components in the recommended order:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    // app.UseCookiePolicy();

    app.UseRouting();
    // app.UseRequestLocalization();
    // app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();
    // app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

在上述代码中:In the preceding code:

  • 在使用单个用户帐户创建新的 Web 应用时未添加的中间件已被注释掉。Middleware that is not added when creating a new web app with individual users accounts is commented out.
  • 并非所有中间件都需要准确按照此顺序运行,但许多中间件必须遵循这个顺序。Not every middleware needs to go in this exact order, but many do. 例如,UseCorsUseAuthenticationUseAuthorization 必须按照上述顺序运行。For example, UseCors, UseAuthentication, and UseAuthorization must go in the order shown.

以下 Startup.Configure 方法将为常见应用方案添加中间件组件:The following Startup.Configure method adds middleware components for common app scenarios:

  1. 异常/错误处理Exception/error handling
    • 当应用在开发环境中运行时:When the app runs in the Development environment:
      • 开发人员异常页中间件 (UseDeveloperExceptionPage) 报告应用运行时错误。Developer Exception Page Middleware (UseDeveloperExceptionPage) reports app runtime errors.
      • 数据库错误页中间件报告数据库运行时错误。Database Error Page Middleware reports database runtime errors.
    • 当应用在生产环境中运行时:When the app runs in the Production environment:
      • 异常处理程序中间件 (UseExceptionHandler) 捕获以下中间件中引发的异常。Exception Handler Middleware (UseExceptionHandler) catches exceptions thrown in the following middlewares.
      • HTTP 严格传输安全协议 (HSTS) 中间件 (UseHsts) 添加 Strict-Transport-Security 标头。HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) adds the Strict-Transport-Security header.
  2. HTTPS 重定向中间件 (UseHttpsRedirection) 将 HTTP 请求重定向到 HTTPS。HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.
  3. 静态文件中间件 (UseStaticFiles) 返回静态文件,并简化进一步请求处理。Static File Middleware (UseStaticFiles) returns static files and short-circuits further request processing.
  4. Cookie 策略中间件 (UseCookiePolicy) 使应用符合欧盟一般数据保护条例 (GDPR) 规定。Cookie Policy Middleware (UseCookiePolicy) conforms the app to the EU General Data Protection Regulation (GDPR) regulations.
  5. 用于路由请求的路由中间件 (UseRouting)。Routing Middleware (UseRouting) to route requests.
  6. 身份验证中间件 (UseAuthentication) 尝试对用户进行身份验证,然后才会允许用户访问安全资源。Authentication Middleware (UseAuthentication) attempts to authenticate the user before they're allowed access to secure resources.
  7. 用于授权用户访问安全资源的授权中间件 (UseAuthorization)。Authorization Middleware (UseAuthorization) authorizes a user to access secure resources.
  8. 会话中间件 (UseSession) 建立和维护会话状态。Session Middleware (UseSession) establishes and maintains session state. 如果应用使用会话状态,请在 Cookie 策略中间件之后和 MVC 中间件之前调用会话中间件。If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.
  9. 用于将 Razor Pages 终结点添加到请求管道的终结点路由中间件(带有 MapRazorPagesUseEndpoints)。Endpoint Routing Middleware (UseEndpoints with MapRazorPages) to add Razor Pages endpoints to the request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

在前面的示例代码中,每个中间件扩展方法都通过 Microsoft.AspNetCore.Builder 命名空间在 IApplicationBuilder 上公开。In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.

UseExceptionHandler 是添加到管道的第一个中间件组件。UseExceptionHandler is the first middleware component added to the pipeline. 因此,异常处理程序中间件可捕获稍后调用中发生的任何异常。Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

尽早在管道中调用静态文件中间件,以便它可以处理请求并使其短路,而无需通过剩余组件。Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. 静态文件中间件不 提供授权检查。The Static File Middleware provides no authorization checks. 可公开访问由静态文件中间件服务的任何文件,包括 wwwroot 下的文件。Any files served by Static File Middleware, including those under wwwroot, are publicly available. 若要了解如何保护静态文件,请参阅 ASP.NET Core 中的静态文件For an approach to secure static files, see ASP.NET Core 中的静态文件.

如果静态文件中间件未处理请求,则请求将被传递给执行身份验证的身份验证中间件 (UseAuthentication)。If the request isn't handled by the Static File Middleware, it's passed on to the Authentication Middleware (UseAuthentication), which performs authentication. 身份验证不使未经身份验证的请求短路。Authentication doesn't short-circuit unauthenticated requests. 虽然身份验证中间件对请求进行身份验证,但仅在 MVC 选择特定 Razor 页或 MVC 控制器和操作后,才发生授权(和拒绝)。Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.

以下示例演示中间件排序,其中静态文件的请求在响应压缩中间件前由静态文件中间件进行处理。The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. 使用此中间件顺序不压缩静态文件。Static files aren't compressed with this middleware order. 可以压缩 Razor Pages 响应。The Razor Pages responses can be compressed.

public void Configure(IApplicationBuilder app)
{
    // Static files aren't compressed by Static File Middleware.
    app.UseStaticFiles();

    app.UseResponseCompression();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    // app.UseRequestLocalization();
    // app.UseCors();

    app.UseAuthentication();
    // app.UseSession();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

在上述代码中:In the preceding code:

  • 在使用单个用户帐户创建新的 Web 应用时未添加的中间件已被注释掉。Middleware that is not added when creating a new web app with individual users accounts is commented out.
  • 并非所有中间件都需要准确按照此顺序运行,但许多中间件必须遵循这个顺序。Not every middleware needs to go in this exact order, but many do. 例如,UseCorsUseAuthentication 必须按照上述顺序运行。For example, UseCors and UseAuthentication must go in the order shown.

以下 Startup.Configure 方法将为常见应用方案添加中间件组件:The following Startup.Configure method adds middleware components for common app scenarios:

  1. 异常/错误处理Exception/error handling
    • 当应用在开发环境中运行时:When the app runs in the Development environment:
      • 开发人员异常页中间件 (UseDeveloperExceptionPage) 报告应用运行时错误。Developer Exception Page Middleware (UseDeveloperExceptionPage) reports app runtime errors.
      • 数据库错误页中间件 (Microsoft.AspNetCore.Builder.DatabaseErrorPageExtensions.UseDatabaseErrorPage) 报告数据库运行时错误。Database Error Page Middleware (Microsoft.AspNetCore.Builder.DatabaseErrorPageExtensions.UseDatabaseErrorPage) reports database runtime errors.
    • 当应用在生产环境中运行时:When the app runs in the Production environment:
      • 异常处理程序中间件 (UseExceptionHandler) 捕获以下中间件中引发的异常。Exception Handler Middleware (UseExceptionHandler) catches exceptions thrown in the following middlewares.
      • HTTP 严格传输安全协议 (HSTS) 中间件 (UseHsts) 添加 Strict-Transport-Security 标头。HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) adds the Strict-Transport-Security header.
  2. HTTPS 重定向中间件 (UseHttpsRedirection) 将 HTTP 请求重定向到 HTTPS。HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.
  3. 静态文件中间件 (UseStaticFiles) 返回静态文件,并简化进一步请求处理。Static File Middleware (UseStaticFiles) returns static files and short-circuits further request processing.
  4. Cookie 策略中间件 (UseCookiePolicy) 使应用符合欧盟一般数据保护条例 (GDPR) 规定。Cookie Policy Middleware (UseCookiePolicy) conforms the app to the EU General Data Protection Regulation (GDPR) regulations.
  5. 身份验证中间件 (UseAuthentication) 尝试对用户进行身份验证,然后才会允许用户访问安全资源。Authentication Middleware (UseAuthentication) attempts to authenticate the user before they're allowed access to secure resources.
  6. 会话中间件 (UseSession) 建立和维护会话状态。Session Middleware (UseSession) establishes and maintains session state. 如果应用使用会话状态,请在 Cookie 策略中间件之后和 MVC 中间件之前调用会话中间件。If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.
  7. MVC (UseMvc) 将 MVC 添加到请求管道。MVC (UseMvc) to add MVC to the request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseSession();
    app.UseMvc();
}

在前面的示例代码中,每个中间件扩展方法都通过 Microsoft.AspNetCore.Builder 命名空间在 IApplicationBuilder 上公开。In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.

UseExceptionHandler 是添加到管道的第一个中间件组件。UseExceptionHandler is the first middleware component added to the pipeline. 因此,异常处理程序中间件可捕获稍后调用中发生的任何异常。Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

尽早在管道中调用静态文件中间件,以便它可以处理请求并使其短路,而无需通过剩余组件。Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. 静态文件中间件不 提供授权检查。The Static File Middleware provides no authorization checks. 可公开访问由静态文件中间件服务的任何文件,包括 wwwroot 下的文件。Any files served by Static File Middleware, including those under wwwroot, are publicly available. 若要了解如何保护静态文件,请参阅 ASP.NET Core 中的静态文件For an approach to secure static files, see ASP.NET Core 中的静态文件.

如果静态文件中间件未处理请求,则请求将被传递给执行身份验证的身份验证中间件 (UseAuthentication)。If the request isn't handled by the Static File Middleware, it's passed on to the Authentication Middleware (UseAuthentication), which performs authentication. 身份验证不使未经身份验证的请求短路。Authentication doesn't short-circuit unauthenticated requests. 虽然身份验证中间件对请求进行身份验证,但仅在 MVC 选择特定 Razor 页或 MVC 控制器和操作后,才发生授权(和拒绝)。Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.

以下示例演示中间件排序,其中静态文件的请求在响应压缩中间件前由静态文件中间件进行处理。The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. 使用此中间件顺序不压缩静态文件。Static files aren't compressed with this middleware order. 可以压缩来自 UseMvcWithDefaultRoute 的 MVC 响应。The MVC responses from UseMvcWithDefaultRoute can be compressed.

public void Configure(IApplicationBuilder app)
{
    // Static files aren't compressed by Static File Middleware.
    app.UseStaticFiles();

    app.UseResponseCompression();

    app.UseMvcWithDefaultRoute();
}

Use、Run 和 MapUse, Run, and Map

使用 UseRunMap 配置 HTTP 管道。Configure the HTTP pipeline using Use, Run, and Map. Use 方法可使管道短路(即不调用 next 请求委托)。The Use method can short-circuit the pipeline (that is, if it doesn't call a next request delegate). Run 是一种约定,并且某些中间件组件可公开在管道末尾运行的 Run[Middleware] 方法。Run is a convention, and some middleware components may expose Run[Middleware] methods that run at the end of the pipeline.

Map 扩展用作约定来创建管道分支。Map extensions are used as a convention for branching the pipeline. Map 基于给定请求路径的匹配项来创建请求管道分支。Map branches the request pipeline based on matches of the given request path. 如果请求路径以给定路径开头,则执行分支。If the request path starts with the given path, the branch is executed.

public class Startup
{
    private static void HandleMapTest1(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map Test 1");
        });
    }

    private static void HandleMapTest2(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map Test 2");
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Map("/map1", HandleMapTest1);

        app.Map("/map2", HandleMapTest2);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
        });
    }
}

下表使用前面的代码显示来自 http://localhost:1234 的请求和响应。The following table shows the requests and responses from http://localhost:1234 using the previous code.

请求Request 响应Response
localhost:1234localhost:1234 Hello from non-Map delegate.Hello from non-Map delegate.
localhost:1234/map1localhost:1234/map1 Map Test 1Map Test 1
localhost:1234/map2localhost:1234/map2 Map Test 2Map Test 2
localhost:1234/map3localhost:1234/map3 Hello from non-Map delegate.Hello from non-Map delegate.

使用 Map 时,将从 HttpRequest.Path 中删除匹配的路径段,并针对每个请求将该路径段追加到 HttpRequest.PathBaseWhen Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.

MapWhen 基于给定谓词的结果创建请求管道分支。MapWhen branches the request pipeline based on the result of the given predicate. Func<HttpContext, bool> 类型的任何谓词均可用于将请求映射到管道的新分支。Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline. 在以下示例中,谓词用于检测查询字符串变量 branch 是否存在:In the following example, a predicate is used to detect the presence of a query string variable branch:

public class Startup
{
    private static void HandleBranch(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            var branchVer = context.Request.Query["branch"];
            await context.Response.WriteAsync($"Branch used = {branchVer}");
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.MapWhen(context => context.Request.Query.ContainsKey("branch"),
                               HandleBranch);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
        });
    }
}

下表使用前面的代码显示来自 http://localhost:1234 的请求和响应。The following table shows the requests and responses from http://localhost:1234 using the previous code.

请求Request 响应Response
localhost:1234localhost:1234 Hello from non-Map delegate.Hello from non-Map delegate.
localhost:1234/?branch=masterlocalhost:1234/?branch=master Branch used = masterBranch used = master

Map 支持嵌套,例如:Map supports nesting, for example:

app.Map("/level1", level1App => {
    level1App.Map("/level2a", level2AApp => {
        // "/level1/level2a" processing
    });
    level1App.Map("/level2b", level2BApp => {
        // "/level1/level2b" processing
    });
});

此外,Map 还可同时匹配多个段:Map can also match multiple segments at once:

public class Startup
{
    private static void HandleMultiSeg(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map multiple segments.");
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Map("/map1/seg1", HandleMultiSeg);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from non-Map delegate.");
        });
    }
}

内置中间件Built-in middleware

ASP.NET Core 附带以下中间件组件。ASP.NET Core ships with the following middleware components. “顺序” 列提供备注,以说明中间件在请求处理管道中的放置,以及中间件可能会终止请求处理的条件。The Order column provides notes on middleware placement in the request processing pipeline and under what conditions the middleware may terminate request processing. 如果中间件让请求处理管道短路,并阻止下游中间件进一步处理请求,它被称为“终端中间件” 。When a middleware short-circuits the request processing pipeline and prevents further downstream middleware from processing a request, it's called a terminal middleware. 若要详细了解短路,请参阅使用 IApplicationBuilder 创建中间件管道部分。For more information on short-circuiting, see the Create a middleware pipeline with IApplicationBuilder section.

中间件Middleware 描述Description 顺序Order
身份验证Authentication 提供身份验证支持。Provides authentication support. 在需要 HttpContext.User 之前。Before HttpContext.User is needed. OAuth 回叫的终端。Terminal for OAuth callbacks.
Cookie 策略Cookie Policy 跟踪用户是否同意存储个人信息,并强制实施 cookie 字段(如 secureSameSite)的最低标准。Tracks consent from users for storing personal information and enforces minimum standards for cookie fields, such as secure and SameSite. 在发出 cookie 的中间件之前。Before middleware that issues cookies. 示例:身份验证、会话、MVC (TempData)。Examples: Authentication, Session, MVC (TempData).
CORSCORS 配置跨域资源共享。Configures Cross-Origin Resource Sharing. 在使用 CORS 的组件之前。Before components that use CORS.
诊断Diagnostics 提供新应用的开发人员异常页、异常处理、状态代码页和默认网页的几个单独的中间件。Several separate middlewares that provide a developer exception page, exception handling, status code pages, and the default web page for new apps. 在生成错误的组件之前。Before components that generate errors. 异常终端或为新应用提供默认网页的终端。Terminal for exceptions or serving the default web page for new apps.
转接头Forwarded Headers 将代理标头转发到当前请求。Forwards proxied headers onto the current request. 在使用已更新字段的组件之前。Before components that consume the updated fields. 示例:方案、主机、客户端 IP、方法。Examples: scheme, host, client IP, method.
运行状况检查Health Check 检查 ASP.NET Core 应用及其依赖项的运行状况,如检查数据库可用性。Checks the health of an ASP.NET Core app and its dependencies, such as checking database availability. 如果请求与运行状况检查终结点匹配,则为终端。Terminal if a request matches a health check endpoint.
HTTP 方法重写HTTP Method Override 允许传入 POST 请求重写方法。Allows an incoming POST request to override the method. 在使用已更新方法的组件之前。Before components that consume the updated method.
HTTPS 重定向HTTPS Redirection 将所有 HTTP 请求重定向到 HTTPS。Redirect all HTTP requests to HTTPS. 在使用 URL 的组件之前。Before components that consume the URL.
HTTP 严格传输安全性 (HSTS)HTTP Strict Transport Security (HSTS) 添加特殊响应标头的安全增强中间件。Security enhancement middleware that adds a special response header. 在发送响应之前,修改请求的组件之后。Before responses are sent and after components that modify requests. 示例:转接头、URL 重写。Examples: Forwarded Headers, URL Rewriting.
MVCMVC 用 MVC/Razor Pages 处理请求。Processes requests with MVC/Razor Pages. 如果请求与路由匹配,则为终端。Terminal if a request matches a route.
OWINOWIN 与基于 OWIN 的应用、服务器和中间件进行互操作。Interop with OWIN-based apps, servers, and middleware. 如果 OWIN 中间件处理完请求,则为终端。Terminal if the OWIN Middleware fully processes the request.
响应缓存Response Caching 提供对缓存响应的支持。Provides support for caching responses. 在需要缓存的组件之前。Before components that require caching.
响应压缩Response Compression 提供对压缩响应的支持。Provides support for compressing responses. 在需要压缩的组件之前。Before components that require compression.
请求本地化Request Localization 提供本地化支持。Provides localization support. 在对本地化敏感的组件之前。Before localization sensitive components.
终结点路由Endpoint Routing 定义和约束请求路由。Defines and constrains request routes. 用于匹配路由的终端。Terminal for matching routes.
会话Session 提供对管理用户会话的支持。Provides support for managing user sessions. 在需要会话的组件之前。Before components that require Session.
静态文件Static Files 为提供静态文件和目录浏览提供支持。Provides support for serving static files and directory browsing. 如果请求与文件匹配,则为终端。Terminal if a request matches a file.
URL 重写URL Rewrite 提供对重写 URL 和重定向请求的支持。Provides support for rewriting URLs and redirecting requests. 在使用 URL 的组件之前。Before components that consume the URL.
WebSocketsWebSockets 启用 WebSockets 协议。Enables the WebSockets protocol. 在接受 WebSocket 请求所需的组件之前。Before components that are required to accept WebSocket requests.

其他资源Additional resources