[Asp.net core]自定义中间件

我们知道在asp.net中每次请求,都要经过请求管道,依次触发管道中的一系列事件。那么我们可以这么理解,中间件是请求管道中的一个组件,可以用来拦截请求,以方便我们进行请求和响应处理,中间件可以定义多个,每一个中间件都可以对管道中的请求进行拦截,它可以决定是否将请求转移给下一个中间件。

中间件如何工作?

默认情况下,中间件的执行顺序根据Startup.cs文件中,在public void Configure(IApplicationBuilder app){} 方法中注册的先后顺序执行。
大概有3种方式可以在管道中注册"中间件"

  1. app.Use()IApplicationBuilder接口原生提供,注册等都用它。
  2. app.Run() ,是一个扩展方法,它需要一个RequestDelegate委托,里面包含了Http的上下文信息,没有next参数,因为它总是在管道最后一步执行。
  3. app.Map(),也是一个扩展方法,类似于MVC的路由,用途一般是一些特殊请求路径的处理。如:www.example.com/token 等。

上面的Run,Map内部也是调用的Use,算是对IApplicationBuilder接口扩充,如果你觉得名字都不够准确,那么下面这个扩展方法就是正宗的注册中间件的了,也是功能最强大的
app.UseMiddleware<>(), 为什么说功能强大呢?是因为它不但提供了注册中间件的功能,还提供了依赖注入(DI)的功能,以后大部分情况就用它了。

asp.net core 提供了IApplicationBuilder接口来让把中间件注册到asp.net的管道请求当中去。那么我们现在自定义一个中间件的功能,比如打印请求的客户端ip功能。

自定义中间件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Wolfy.IPDemo.Middlewares
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class IPMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        public IPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<IPMiddleware>();
        }

        public Task Invoke(HttpContext httpContext)
        {
            _logger.LogInformation($"Client Ip:{httpContext.Connection.RemoteIpAddress.ToString()}");
            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class IPMiddlewareExtensions
    {
        public static IApplicationBuilder UseIP(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<IPMiddleware>();
        }
    }
}

该如何使用我们定义的中间件?

在startup.cs中启用中间件

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseIP();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

直接运行程序

以这种方式运行程序,是以使用Kestrel为宿主服务器运行的。

运行结果

总结

本篇文章介绍了,如何自定义中间件,以及如何使用定义的中间件,那么在什么场景下使用中间件?个人认为,如果和业务关系不大的功能,可以定义为中间件,方便使用。

posted @ 2017-09-28 10:39  wolfy  阅读(2170)  评论(1编辑  收藏  举报