ASP.NET Core -中间件(Middleware)使用
ASP.NET Core開(kāi)發(fā),開(kāi)發(fā)并使用中間件(Middleware)。
中間件是被組裝成一個(gè)應(yīng)用程序管道來(lái)處理請(qǐng)求和響應(yīng)的軟件組件。
每個(gè)組件選擇是否傳遞給管道中的下一個(gè)組件的請(qǐng)求,并能之前和下一組分在管道中調(diào)用之后執(zhí)行特定操作。
具體如圖:
?
開(kāi)發(fā)中間件(Middleware)
今天我們來(lái)實(shí)現(xiàn)一個(gè)記錄ip 的中間件。
1.新建一個(gè)asp.net core項(xiàng)目,選擇空的模板。
2.新建一個(gè)類(lèi):?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.再新建一個(gè):RequestIPExtensions.cs
public static class RequestIPExtensions{public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder){return builder.UseMiddleware<RequestIPMiddleware>();}}這樣我們就編寫(xiě)好了一個(gè)中間件。
使用中間件(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!");});}然后運(yùn)行程序,我選擇使用Kestrel 。
訪問(wèn):http://localhost:5000/
成功運(yùn)行。
二、Asp.Net Core使用中間件攔截處理請(qǐng)求
public class OuterImgMiddleware {public static string RootPath { get; set; } //配置文件讀取絕對(duì)位置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()中注冊(cè)使用就可以了。
?
更多:
Asp.Net Core 通過(guò)自定義中間件防止圖片盜鏈的實(shí)例(轉(zhuǎn))
在ASP.NET Core2.0中使用百度在線編輯器UEditor(轉(zhuǎn))
Asp.Net Core WebAPI入門(mén)整理(四)參數(shù)獲取
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core -中间件(Middleware)使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Docker镜像的基本操作
- 下一篇: Android App解决卡顿慢之内存抖