.net core 利用中間件處理常見的網站功能 包括 session、routers、重定向、重寫和文件下載

在.net core中全部的請求都會被請求中間件所處理,因此咱們能夠經過在中間件裏邊添加對應的功能而後在服務中添加註入來實現對應的功能 html

文件位置:Startup.cs=>Configure方法,請求中間件的代碼位置session

1.什麼是中間件:mvc

中間件是組裝成應用程序管道以處理請求和響應的軟件。每一個組件選擇是否將請求傳遞給流水線中的下一個組件,而且能夠在管道中調用下一個組件以前和以後執行某些操做。請求代理用於構建請求管道。請求委託處理每一個HTTP請求。app

 

這張圖已經說的很明白了,就是請求會被中間件一個接一個的處理完畢,最後才返回給客戶ide

給出一箇中間件的範例:函數

在網站的根目錄建立類文件,而後就能夠在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)是實現對象與其協做者或依賴關係之間鬆散耦合的技術。爲了執行其操做,類須要的對象不是直接實例化協做者,或使用靜態引用,而是以某種方式提供給類。大多數狀況下,類將經過它們的構造函數聲明它們的依賴關係,容許它們遵循顯式依賴原則。這種方法被稱爲「構造器注入」。ui

值得注意的是構造器注入的參數必須支持默認值this

public CharactersController(ICharacterRepository characterRepository, string title = "Characters")
{
    _characterRepository = characterRepository;
    _title = title;
}

1.session ,添加方式:

1.ConfigureServices中添加:
 
services.AddSession();//使服務支持Session
 
2.在Configure中添加
            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:

一樣須要執行這些操做:

 1.ConfigureServices中添加:
services.AddRouting();
2.Configure中添加
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);

到這步就能夠執行對應文件的下載了

文件結構以下:

運行效果圖:

 

相關文章
相關標籤/搜索