ASP.Net Core 是微软开源的跨平台、可扩大、轻量级的模块化框架,可用于构建高性能的web应用程序。中间件组件能够注入到 ASP.Net Core 申请管道中实现对 Request 和 Response 的定制和批改。

ASP.Net Core 中间件能够用于查看、路由或者批改流转于Pipeline的Request和Response。本文将会探讨如何应用这些中间件来实现一些高级操作。

Use,Run,Map办法介绍

Use、Map,Run办法罕用来一起构建 HTTP Pipeline 管道,上面疾速浏览一下这些办法和它们的用处。

  • Use

该办法将会执行一个委托,而后将 交接棒 传给Pipeline的下一个中间件,因该办法短暂领有 交接棒,所以该办法可用于 短路操作

  • Run

该办法会执行委托并返回后果。

  • Map

该办法将有条件地执行委托并返回后果。

注册中间件

中间件是在 Startup.Configure 中进行注册,调用办法就是 Use* 系列扩大办法,上面是注册中间件的语法。

public void Configure(IApplicationBuilder app, IHostingEnvironment env){    app.UseMyCustomMiddleware<MyCustomMiddleware>();}

须要留神的是,中间件的执行程序和你注册的程序是保持一致的。

Invoke 办法

每个中间件都蕴含一个 Invoke() 办法, 这个办法参数是 HttpContext 的一个实例,本中间件的业务逻辑会在下一个中间件的执行前后都会被执行,如果你有点懵的话,能够理解一下什么叫:递归调用,如上面代码正文所示:

public async Task Invoke(HttpContext context){    // Write code here that will be executed before the    // next middleware is called        await _next.Invoke(context); // call next middleware    // Write code here that will be executed after the    //next middleware is called }

分流 Http 管道

Map系扩大办法,比方:Map 和 MapWhen,它们罕用于给 pipeline 管道操作进行分流,前者是基于 Request path 进行分流,后者是基于指定的 谓语动词 进行分流。

上面的代码片段展现了如何应用 Map 办法对 Request Pipeline 进行分流。

public class Startup{    private static void MapRequestA(IApplicationBuilder app)    {        app.Run(async context =>        {            await context.Response.WriteAsync("This is MapRequestA");        });    }    private static void MapRequestB(IApplicationBuilder app)    {        app.Run(async context =>        {            await context.Response.WriteAsync("This is MapRequestB");        });    }    private static void MapRequestC(IApplicationBuilder app)    {        app.Run(async context =>        {            await context.Response.WriteAsync("This is MapRequestC");        });    }    public void Configure(IApplicationBuilder app)    {        app.Map("/mapRequestPathA", MapRequestA);        app.Map("/mapRequestPathB", MapRequestB);        app.Map("/mapRequestPathB", MapRequestC);        app.Run(async context =>        {            await context.Response.WriteAsync("Hello World!");        });    }   //Other methods}

MapWhen 办法承受两个参数:

  • Func<HttpContext, bool> predicate
  • delegate action

你能够在 Startup.Configure 办法中回绝 text/xml 格局的 request,如下代码所示:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            app.MapWhen(context => context.Request.ContentType.Equals            ("text/xml", StringComparison.InvariantCultureIgnoreCase),            (IApplicationBuilder applicationBuilder) =>            {                applicationBuilder.Run(async context =>                {                    await Task.FromResult(context.Response.StatusCode = StatusCodes.Status406NotAcceptable);                });            });            app.UseMvc();        }

应用 UseWhen

UseWhen办法能够用于有条件的执行中间件,上面的代码片段展现了如果以后 Request 申请门路是以 /api 结尾的话,执行一个指定的中间件,代码如下:

app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>{    applicationBuilder.UseCustomMiddleware();});

请留神,UseWhen 不像 MapWhen,前者会继续执行前面的中间件逻辑,不论以后 UseWhen 的委托函数返回的是 true 还是 false,如果有点懵的话,能够了解一下上面的代码:

app.UseMiddlewareA();app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>{    applicationBuilder.UseMiddlewareB();});app.UseMiddlewareC();

如果中间件没有短路,那么中间件A和C必定会被执行的,而且当申请门路是以 /api 结尾时,中间件B也会被调度。

ASP.Net Core 申请解决管道中有一个中间件链,所有申请和响应都流经此管道,当新申请达到时,这些中间件要么解决申请,要么将申请传递给管道中的下一个组件,对于更简单的申请解决,咱们能够应用 Map 和 MapWhen 办法来分流管道,并能够应用 UseWhen 有条件的执行中间件。

译文链接:https://www.infoworld.com/art...

更多高质量干货:参见我的 GitHub: csharptranslate