zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    bzoj 4911: [Sdoi2017]切树游戏
    bzoj 2654: tree
    bzoj 3240: [Noi2013]矩阵游戏
    有标号的DAG计数 III
    有标号的DAG计数 II
    bzoj 3512: DZY Loves Math IV
    bzoj 4480: [Jsoi2013]快乐的jyy
    bzoj 5323: [Jxoi2018]游戏
    codeforces412A
    7.6 T1 深度优先搜索(dfs)
  • 原文地址:https://www.cnblogs.com/gaobing/p/12572786.html
Copyright © 2011-2022 走看看