在.net core中所有的請求都會被請求中間件所處理,所以我們可以通過在中間件里邊添加對應的功能然后在服務中添加注入來實現對應的功能
文件位置:Startup.cs=>Configure方法,請求中間件的代碼位置
1.什么是中間件:
中間件是組裝成應用程序管道以處理請求和響應的軟件。每個組件選擇是否將請求傳遞給流水線中的下一個組件,並且可以在管道中調用下一個組件之前和之后執行某些操作。請求代理用於構建請求管道。請求委托處理每個HTTP請求。

這張圖已經說的很明白了,就是請求會被中間件一個接一個的處理完畢,最后才返回給客戶
給出一個中間件的范例:
在網站的根目錄創建類文件,然后就可以在Startup.cs=>Configure 中用以app.AddLog();的方式來調用自定義添加的中間件
public static class newclass { public static IApplicationBuilder AddLog(this IApplicationBuilder app) { new Common.Log.LogFactory().GetLog("中間件測試").Debug(true,"被執行"); return app; } }
2.依賴注入
依賴注入(DI)是實現對象與其協作者或依賴關系之間松散耦合的技術。為了執行其操作,類需要的對象不是直接實例化協作者,或使用靜態引用,而是以某種方式提供給類。大多數情況下,類將通過它們的構造函數聲明它們的依賴關系,允許它們遵循顯式依賴原則。這種方法被稱為“構造器注入”。
值得注意的是構造器注入的參數必須支持默認值
public CharactersController(ICharacterRepository characterRepository, string title = "Characters") { _characterRepository = characterRepository; _title = title; }
1.session ,添加方式:
SessionOptions os=new SessionOptions(); os.IdleTimeout=new TimeSpan(0,0,15); app.UseSession(os);
3.測試
在Controller中添加引用:using Microsoft.AspNetCore.Http;
在控制器中添加:
HttpContext.Session.SetString(Guid.NewGuid().ToString(),Guid.NewGuid().ToString());
執行控制器就可以看到效果。
routers:
同樣需要執行這些操作:
services.AddRouting();
var trackPackageRouteHandler = new RouteHandler(context => { StringBuilder sessionstr= new StringBuilder(); sessionstr.Append("當前可用session有:<br/>"); foreach(string s in context.Session.Keys) { sessionstr.Append("key:"+s+",value:"+context.Session.GetString(s)+"<br/>"); } context.Response.Headers.Add("Content-Type","text/html;charset=UTF8"); return context.Response.WriteAsync(sessionstr.ToString()); }); var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler); routeBuilder.MapRoute( "GetSessoin", "Session"); var routes = routeBuilder.Build(); app.UseRouter(routes);
3.執行完第一步session的添加如果成功的話,執行完添加session的控制器,再執行 localhost:5000/session就能看到當前的session值
注:這里的router只是一部分,還包含mvc下的router規則,他們之間的關系是與的關系,也就是說,不管是在mvc中定義的規則,還是這里定義的規則都會執行。
重定向和重寫,這里實現一個簡單的文件下載功能,符合我的路由規則,就下載對應的文件
1.要實現如上功能需要添加對 Microsoft.AspNetCore.Rewrite的引用添加 --nuget Microsoft.AspNetCore.Rewrite ...
2.在Configure中添加代碼
RewriteOptions options = new RewriteOptions() .AddRewrite("^(.*)/(.*)$","xmlOption/Get/$2.$1",true) .AddRedirect("^sf/(.*).xml","xml/$1");//$1--bug app.UseRewriter(options);
解釋一下
AddRewrite("^(.*)/(.*)$","xmlOption/Get/$2.$1",true)
這里的意思就是匹配 任意字符/任意字符 ,滿足條件就執行 xmlOption/Get/$2.$1 這個控制器【$1,$2是占位符】,下同
添加下載的控制器
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.IO; using System.Threading.Tasks; namespace Web.Controllers { public class xmlOptionController : Controller { public void Get(string id) { string filename=id; id = "sf/" + id; if (System.IO.File.Exists(id)) { string filePath = id;//路徑 FileInfo fileInfo = new FileInfo(filePath); HttpContext.Response.Clear(); HttpContext.Response.Headers.Add("Content-Disposition", "attachment;filename=" + filename); HttpContext.Response.Headers.Add("Content-Length", fileInfo.Length.ToString()); HttpContext.Response.Headers.Add("Content-Transfer-Encoding", "binary"); HttpContext.Response.ContentType = "application/octet-stream"; Task t = HttpContext.Response.SendFileAsync(id,0,fileInfo.Length); t.Wait(); } else { HttpContext.Response.Headers.Add("Content-type", "text/html;charset=UTF-8"); HttpContext.Response.WriteAsync("文件不存在"); } } } }
在添加控制器之前需要將靜態文件夾sf添加到項目的靜態文件中,同樣需要在Configure中添加靜態文件夾引用
StaticFileOptions so=new StaticFileOptions(); so.FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"sf"));//這里的文件名稱是真實的文件名稱 so.RequestPath="/sf";//這里的/sf就是程序中映射的路徑 app.UseStaticFiles(so);
到這步就可以執行對應文件的下載了
文件結構如下:

運行效果圖:


