ASP.NET Core開發,開發並使用中間件(Middleware)。html
中間件是被組裝成一個應用程序管道來處理請求和響應的軟件組件。app
每一個組件選擇是否傳遞給管道中的下一個組件的請求,並能以前和下一組分在管道中調用以後執行特定操做。asp.net
具體如圖:async
今天咱們來實現一個記錄ip 的中間件。編輯器
1.新建一個asp.net core項目,選擇空的模板。ui
2.新建一個類: RequestIPMiddleware.csthis
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.csspa
public static class RequestIPExtensions { public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestIPMiddleware>(); } }
這樣咱們就編寫好了一箇中間件。.net
1.使用code
在 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/
成功運行。
2、Asp.Net Core使用中間件攔截處理請求
public class OuterImgMiddleware { public static string RootPath { get; set; } //配置文件讀取絕對位置 private readonly RequestDelegate _next; public OuterImgMiddleware(RequestDelegate next, IHostingEnvironment env) { // _wwwrootFolder = env.WebRootPath; _next = next; } public async Task Invoke(HttpContext context) { var path = context.Request.Path.ToString(); var headersDictionary = context.Request.Headers; if (context.Request.Method == "GET") if (!string.IsNullOrEmpty(path) && path.Contains("/upload/logo")) { //var unauthorizedImagePath = Path.Combine(RootPath, path); var unauthorizedImagePath = RootPath + path; await context.Response.SendFileAsync(unauthorizedImagePath); return; } await _next(context); } }
public static class MvcExtensions { public static IApplicationBuilder UseOutImg(this IApplicationBuilder builder) { return builder.UseMiddleware<OuterImgMiddleware>(); } }
同上在Configure()中註冊使用就能夠了。
更多:
Asp.Net Core 經過自定義中間件防止圖片盜鏈的實例(轉)