自定义中间件

我们知道在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 中间件
自定义中间件

猜你喜欢

转载自www.cnblogs.com/kw13202/p/11465128.html