Custom Middleware

We know that every request in asp.net, go through the request pipeline, which in turn triggers a series of events in the pipeline. Then we can understand, a middleware component is a request pipeline, can be used to intercept the request, to facilitate our request and response processing, middleware can define multiple, each broker in the pipeline may request interception, it can decide whether to request a transfer to the next middleware.

Custom Middleware

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);
        }
    }
}

Add extension method

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

In startup.csenabled middleware

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    app.UseReq();

    // 使用MVC
    app.UseMvc();
}

Reference:
write custom ASP.NET Core middleware
ASP.NET Core middleware,
custom middleware

Guess you like

Origin www.cnblogs.com/kw13202/p/11465128.html
Recommended