Skip to content

Middleware

Edward edited this page Aug 1, 2018 · 1 revision

Asp.NET Core Middleware

什么是Middleware?

Middleware是程序观点内的组件,用于处理RequestsResponses.

  • 可以选择是否将Request传递给下一个Middleware组件
  • 可以在引入下一个组件之前和之后进行一些操作

Request Delegate 用于建立请求管道,并处理每一个请求。

  • 通过Run, MapUse配置Request Delegate
  • 通过in-line as an anonymous method(called in-line middleware)和reusable class定义
  • Middleware可以引入下一个Middleware或者结束通话

Creating a middleware pipeline with IApplicationBuilder

Asp.Net Core Request pipeline

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

避免在Response返回给客户端之后调用next.Invoke, 在Response开始之后修改HttpResponse会抛出Exception.

HttpResponse.HasStarted可以判断Response是否被返回,headers是否被设置body是否被写入

Ordering

public void Configure(IApplicationBuilder app)
{
    app.UseExceptionHandler("/Home/Error"); // Call first to catch exceptions
                                            // thrown in the following middleware.

    app.UseStaticFiles();                   // Return static files and end pipeline.

    app.UseAuthentication();               // Authenticate before you access
                                           // secure resources.

    app.UseMvcWithDefaultRoute();          // Add MVC to the request pipeline.
}
  • UseExceptionHandler用于pipeline的第一行,可以捕获Request的所有异常
  • UseStaticFiles 配置在pipeline的前部,可以处理请求并且短回路请求,避免进去剩下的组件。static file middleware 没有提供Authorization的检查,是publicly available
  • UseAuthentication 进行AuthenticationIdentity不会short-circuit 未认证的请求。
  • Although Identity authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or controller and action.

Use, Run, and Map

  • app.Run 终结管道
  • app.Use 配置多个request delegate,可以通过不调用next来终结管道
  • 可以在next delegate之前或者之后执行操作
  • Map 基于给定的Request path来分发请求管道, Map必须以/符号开始,比如app.Map("/map1".

Map

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

MapWhen

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

Built-in middleware

Middleware Description Order
Authentication Provides authentication support. Before HttpContext.User is needed. Terminal for OAuth callbacks.
CORS Configures Cross-Origin Resource Sharing. Before components that use CORS.
Diagnostics Configures diagnostics. Before components that generate errors.
Forwarded Headers Forwards proxied headers onto the current request. Before components that consume the updated fields (examples: scheme, host, client IP, method).
HTTP Method Override Allows an incoming POST request to override the method. Before components that consume the updated method.
HTTPS Redirection Redirect all HTTP requests to HTTPS (ASP.NET Core 2.1 or later). Before components that consume the URL.
HTTP Strict Transport Security (HSTS) Security enhancement middleware that adds a special response header (ASP.NET Core 2.1 or later). Before responses are sent and after components that modify requests (for example, Forwarded Headers, URL Rewriting).
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.
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 files.
URL Rewriting Provides support for rewriting URLs and redirecting requests. Before components that consume the URL.
WebSockets Enables the WebSockets protocol. Before components that are required to accept WebSocket requests.

Writing middleware

In ASP.NET Core 1.x, the middleware Task method's name must be Invoke. In ASP.NET Core 2.0 or later, the name can be either Invoke or InvokeAsync.

  • per application lifetime dependencies
  • per request dependencies

Clone this wiki locally