ASP.NET Core -中间件(Middleware)使用
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET Core -中间件(Middleware)使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ASP.NET Core開發,開發并使用中間件(Middleware)。
中間件是被組裝成一個應用程序管道來處理請求和響應的軟件組件。
每個組件選擇是否傳遞給管道中的下一個組件的請求,并能之前和下一組分在管道中調用之后執行特定操作。
具體如圖:
?
開發中間件(Middleware)
今天我們來實現一個記錄ip 的中間件。
1.新建一個asp.net core項目,選擇空的模板。
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/
成功運行。
二、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 通過自定義中間件防止圖片盜鏈的實例(轉)
在ASP.NET Core2.0中使用百度在線編輯器UEditor(轉)
Asp.Net Core WebAPI入門整理(四)參數獲取
總結
以上是生活随笔為你收集整理的ASP.NET Core -中间件(Middleware)使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker镜像的基本操作
- 下一篇: Android App解决卡顿慢之内存抖