ASP.NET Core 3.x 自定义中间件

一、中间件实例

    /// <summary>
    /// 请求日志中间件
    /// </summary>
    public class RequestLogMiddleWare
    {
        private static readonly object o = new object();

        private readonly RequestDelegate _next;

        private readonly ILogger<RequestLogMiddleWare> _logger;

        //flag是可传递的中间件参数,构造函数支持依赖注入
        public RequestLogMiddleWare(ILogger<RequestLogMiddleWare> logger, RequestDelegate next, int flag)
        {
            this._logger = logger;
            this._next = next;
        }

        public Task Invoke(HttpContext context)
        {

            var requestPath = context.Request.Path;
            var logPath = AppDomain.CurrentDomain.BaseDirectory + "request.log";

            lock (o)
            {
                var logDetail = $"date:{DateTime.Now:yyyy-MM-dd HH:mm:ss}----{requestPath}{Environment.NewLine}";

                File.AppendAllText(logPath, logDetail);
            }
       //执行下一个中间件
            _next(context);

            return Task.CompletedTask;
        }
    }

 

二、将中间件写成扩展方法(Usexxx)

 public static class RequestLogExtensions
    {

        public static void UseRequestLog(this IApplicationBuilder app)
        {
            //使用中间件,并传递flag构造参数
            app.UseMiddleware<RequestLogMiddleWare>(10);
        }
    }

 

三、使用中间件扩展方法

app.UseRequestLog();

 

posted @ 2020-03-26 10:49  b̶i̶n̶g̶.̶  阅读(321)  评论(0编辑  收藏  举报