ASP.NET Core開發,開發並使用中間件(Middleware)。html
中間件是被組裝成一個應用程序管道來處理請求和響應的軟件組件。git
每一個組件選擇是否傳遞給管道中的下一個組件的請求,並能以前和下一組分在管道中調用以後執行特定操做。github
具體如圖:app
開發中間件(Middleware)
今天咱們來實現一個記錄ip 的中間件。asp.net
1.新建一個asp.net core項目,選擇空的模板。async
而後爲項目添加一個 Microsoft.Extensions.Logging.Consolepost
NuGet 命令行 ,請使用官方源。ui
Install-Package Microsoft.Extensions.Logging.Console -Prethis
2.新建一個類: RequestIPMiddleware.csspa
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/
成功運行。
這裏咱們還能夠對這個中間件進行進一步改進,增長更多的功能,如限制訪問等。
若是你以爲本文對你有幫助,請點擊「推薦」,謝謝。