ASP.NET Core 定义自己的中间件
- 中间件中间件是一种装配到应用管道以处理请求和响应的软件。 每个组件:选择是否将请求传递到管道中的下一个组件。可在管道中的下一个组件前后执行工作。请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。
中间件执行顺序

自定义中间件:
ASP.NET Core约定中间件类必须包括以下内容:
1、具有类型为RequestDelegate参数的公共构造函数。
2、必须有名为Invoke或InvokeAsync的公共方法,此方法必须满足两个条件:
a. 方法返回类型是Task、
b.方法的第一个参数必须是HttpContext类型。
以记录IP为例:新建IP中间处理类
public class IpLogMiddleware{
private readonly RequestDelegate _next;
public IpLogMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
//可以实现多次读取Body
context.Request.EnableBuffering();
// 请求数据
var request = context.Request;
//输出信息
var url=request.Path.ObjToString().TrimEnd('/').ToLower();
var date=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var ips=GetClientIP(context);
Console.WriteLine($"Datetime:{date},IP:{ips},Url:{url}");
// 调用管道中的下一个委托
await _next(context);
}
public static string GetClientIP(HttpContext context)
{
var ip = context.Request.Headers["X-Forwarded-For"].ObjToString();
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.ObjToString();
}
return ip;
}
}
3.定义一个中间件通用类:
public static class MiddlewareHelpers{
public static IApplicationBuilder UseIpLogMiddle(this IApplicationBuilder app)
{
return app.UseMiddleware();
}
}
4. 使用中间件 app.UseIpLogMiddle();
