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

    我们知道在asp.net中每次请求,都要经过请求管道,依次触发管道中的一系列事件。那么我们可以这么理解,中间件是请求管道中的一个组件,可以用来拦截请求,以方便我们进行请求和响应处理,中间件可以定义多个,每一个中间件都可以对管道中的请求进行拦截,它可以决定是否将请求转移给下一个中间件。

    自定义中间件

    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace dnc
    {
        public class RequestMiddleware
        {
            private readonly RequestDelegate _next;
            private readonly ILogger _logger;
            public RequestMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
            {
                _next = next;
                _logger = loggerFactory.CreateLogger<RequestMiddleware>();
            }
    
            public Task Invoke(HttpContext httpContext)
            {
                _logger.LogInformation($"Path:{ httpContext.Request.Path }");
                _logger.LogInformation($"Client Ip:{httpContext.Connection.RemoteIpAddress.ToString()}");
                return _next(httpContext);
            }
        }
    }
    

    添加扩展方法

    namespace dnc
    {
        public static class MiddlewareExtensions
        {
            public static IApplicationBuilder UseReq(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<RequestMiddleware>();
            }
        }
    }
    

    startup.cs中启用中间件

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        
        app.UseReq();
    
        // 使用MVC
        app.UseMvc();
    }
    

    参考资料:
    写入自定义 ASP.NET Core 中间件
    ASP.NET Core 中间件
    自定义中间件

  • 相关阅读:
    记一次在Windows10桌面环境搭建Jekins的吐血经历
    Windows系统下的输入法选择
    Linux后台进程启停脚本模板
    crontab采坑总结
    编程软件仓库集合
    CentOS7安装Chrome及驱动
    不错的“淘宝”网站
    软件下载网站集合
    在线API集合
    在线教程集合
  • 原文地址:https://www.cnblogs.com/kw13202/p/11465128.html
Copyright © 2011-2022 走看看