剑轩

.NET CORE中间件实现用户IP地址记录

电脑版发表于:2019/7/26 16:31

中间件与过滤器的区别
https://www.tnblog.net/aojiancc2/article/details/2537

创建中间件RequestIPMyMiddleware

public class RequestIPMyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    public RequestIPMyMiddleware(RequestDelegate next, ILoggerFactory logger)
    {
        _next = next;
        _logger = logger.CreateLogger<RequestIPMyMiddleware>();
    }
    /// <summary>
    /// 执行的方法
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation("自定义中间件被执行");
        //执行超作
        _logger.LogInformation("My Ip:" + context.Connection.RemoteIpAddress.ToString());
        //执行下一个中间件
        await _next.Invoke(context);
    }
}


添加中间件的引用


运行效果:


使用扩展方法中转添加中间件
这样使用使用起来就更加方便了

public static class RequestIPMiddlewareExtands
{
    public static IApplicationBuilder UseMyIp(this IApplicationBuilder app)
    {
        //链式编程
        return app.UseMiddleware<RequestIPMyMiddleware>();
    }
}


使用




关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢