zoukankan      html  css  js  c++  java
  • 自定义中间件

    中间件是一种装配到应用管道以处理请求和响应的软件。
    通常,中间件封装在类中,并且通过扩展方法公开。

    约定模式

    自定义类-扩展-注册

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
    /// <summary>
    /// 访问接口耗时
    /// </summary>
    public class CustomInvokeElapseTime
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly Stopwatch _stopwatch;
    
        public CustomInvokeElapseTime(RequestDelegate next)
        {
            _next = next;
            _stopwatch = new Stopwatch();
        }
        public CustomInvokeElapseTime(RequestDelegate next, ILogger logger) : this(next)
        {
            _logger = logger;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            _stopwatch.Restart();
            context.Response.OnCompleted(() =>
            {
                _stopwatch.Stop();
    #if DEBUG
                Console.WriteLine($"ElaspedTime:{_stopwatch.ElapsedMilliseconds} ms");
                _logger.LogInformation($"执行耗时:{_stopwatch.ElapsedMilliseconds} ms");
    #endif
                return Task.CompletedTask;
            });
            await _next(context);
        }
    }
    /// <summary>
    /// 扩展中间件
    /// </summary>
    public static class CustomInvokeElapseTimeExtensions
    {
        public static IApplicationBuilder UseCustomInvokeElapseTime(this IApplicationBuilder app)
        {
            return app.UseMiddleware<CustomInvokeElapseTime>();
        }
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseSession();
    
        logger.LogInformation("自定义中间件添加到管道中");
        app.UseCustomInvokeElapseTime();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX.dll");
        });
    }
    

    基于工厂

    第三方容器

  • 相关阅读:
    BZOJ3403: [Usaco2009 Open]Cow Line 直线上的牛
    lintcode入门篇三
    lintcode入门篇二
    lintcode入门篇一
    matplotlib
    Pandas
    Numpy
    缓存
    Django性能优化的几种方法
    python总结十一
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/14379173.html
Copyright © 2011-2022 走看看