.NetCore中间件的使用及原理分析

.NetCore中加入了中间件,简单记录下使用方法

这里以一个记录访问的IP的值的中间件示例

在StartUp中的Configure方法中进行配置

方法A:

            app.Use(next =>
            {
                return new RequestDelegate(async context =>
                {
                    var ip = context.Connection.RemoteIpAddress;
                    var port = context.Connection.RemotePort;
                    await context.Response.WriteAsync($"Ip:{ip},port:{port}");
                });
            });

方法B:

单独写成一个MiddleWare的类来实现

自定义中间件其实就是这么一个套路,定义public RequestDelegate _next,然后定义方法public async Task Invoke(HttpContext context)执行await _next.Invoke(context)

    //自定义中间件记录ip地址
    public class IPMiddleWare
    {
        public RequestDelegate _next;
        public IPMiddleWare(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            var ip = context.Connection.RemoteIpAddress;
            var port = context.Connection.RemotePort;
            Log4NetHelper.WriteInfoLog(typeof(IPMiddleWare), $"Ip:{ip},port:{port}");
            //await context.Response.WriteAsync($"Ip:{ip},port:{port}");
            await _next.Invoke(context);
        }
    }

然后在StartUp的Configure方法中进行注册

app.UseMiddleware<IPMiddleWare>();

方法C:

按照方法B,只不过将注册方法以扩展方法来实现

    public static class IPMiddleWareExtension
    {
        /// <summary>
        /// IP记录中间件扩展
        /// </summary>
        /// <param name="app"></param>
        public static IApplicationBuilder UseIPLog(this IApplicationBuilder app)
        {
            return app.UseMiddleware<IPMiddleWare>();
        }
    }

然后在StartUp的Configure方法中进行注册

app.UseIPLog();

 

关于中间件的用法,可以看下源码ApplicationBuilder类和UseMiddlewareExtensions类就能大概明白他的设计思路了

UseMiddlewareExtensions的UseMiddleware最终是调用了ApplicationBuilder里的Use方法

Use方法其实就是将一个Func<RequestDelegate, RequestDelegate>委托增加到列表IList<Func<RequestDelegate, RequestDelegate>>中

最后Builde的时候对list进行Reverse然后通过app = component(app); 其中app为RequestDelegate app

这样就可以一个RequestDelegate调用下一个RequestDelegate了,也就实现了中间件可以一层层调用下去了。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值