.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了,也就实现了中间件可以一层层调用下去了。