.NET Core 中间件

中间件是一种装配到应用管道以处理请求和响应的软件。 每个组件:

  1.选择是否将请求传递到管道中的下一个组件。

  2.可在管道中的下一个组件前后执行工作。

请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。
使用 RunMap 和 Use 扩展方法来配置请求委托。 可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在可重用的类中对其进行定义。 这些可重用的类和并行匿名方法即为中间件,也叫中间件组件。 请求管道中的每个中间件组件负责调用管道中的下一个组件,或使管道短路。

使用 IApplicationBuilder 创建中间件管道

ASP.NET Core 请求管道包含一系列请求委托,依次调用。 下图演示了这一概念。 沿黑色箭头执行。


每个委托均可在下一个委托前后执行操作。 此外,委托还可以决定不将请求传递给下一个委托,这就是对请求管道进行短路。 通常需要短路,因为这样可以避免不必要的工作。 例如,静态文件中间件可以返回静态文件请求并使管道的其余部分短路。 先在管道中调用异常处理委托,以便它们可以捕获在管道的后期阶段所发生的异常。

新建一个类RequestIPMiddleware获取ip地址

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

public class RequestIPMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<RequestIPMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation("User IP------->" + context.Connection.RemoteIpAddress.ToString());
        await context.Response.WriteAsync("IP----->"+context.Connection.RemoteIpAddress.ToString() +"\n");
        await _next.Invoke(context);
    }

}
View Code

创建类RequestIPExtensions

using Microsoft.AspNetCore.Builder;

public static class RequestIPExtensions
{
    public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestIPMiddleware>();
    }
}
View Code

然后在Startup类中的Configure方法中调用

 loggerfactory.AddConsole(minLevel: LogLevel.Information);
 app.UseRequestIP(); //使用Ip中间件
 app.Run(async context =>{
       await context.Response.WriteAsync("Hello world !");
  });

参考 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

猜你喜欢

转载自www.cnblogs.com/ZJ199012/p/10348878.html