ASP.NET Core 開發-中間件(Middleware)


ASP.NET Core開發,開發並使用中間件(Middleware)。

中間件是被組裝成一個應用程序管道來處理請求和響應的軟件組件。

每個組件選擇是否傳遞給管道中的下一個組件的請求,並能之前和下一組分在管道中調用之后執行特定操作。

具體如圖:

 

開發中間件(Middleware)

今天我們來實現一個記錄ip 的中間件。

1.新建一個asp.net core項目,選擇空的模板。

然后為項目添加一個 Microsoft.Extensions.Logging.Console

NuGet 命令行 ,請使用官方源。

Install-Package Microsoft.Extensions.Logging.Console -Pre

2.新建一個類: RequestIPMiddleware.cs

    public class RequestIPMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<RequestIPMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {            
            _logger.LogInformation("User IP: " + context.Connection.RemoteIpAddress.ToString());
            await _next.Invoke(context);
        }
    }

 

3.再新建一個:RequestIPExtensions.cs

    public static class RequestIPExtensions
    {
        public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestIPMiddleware>();
        }
    }

這樣我們就編寫好了一個中間件。

使用中間件(Middleware)

1.使用

在 Startup.cs 添加 app.UseRequestIP()

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(minLevel: LogLevel.Information);
            app.UseRequestIP();//使用中間件
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

然后運行程序,我選擇使用Kestrel 。

訪問:http://localhost:5000/

成功運行。

這里我們還可以對這個中間件進行進一步改進,增加更多的功能,如限制訪問等。

 

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM