dotnetCore增加MiddleWare的Run,Use Map MapThen四個擴充方法

來源:互聯網
上載者:User

標籤:

什麼是中介軟體

中介軟體是在管道中處理Request請求與Responses響應的一種組件,每種組件可以選擇是否讓Request進入到下一個組件去處理。

譯得不好,大家可以自己看原文Middleware

更詳細的還可以參照園中大神的作品;

有湯姆大叔的解讀ASP.NET 5 & MVC6系列(6):Middleware詳解 

artech大神的 ASP.NET Core真實管道詳解[1]:中介軟體是個什麼東西?

怎麼建立一個Middleware請參考英文文檔Middleware 或者

LineZero的 ASP.NET Core 開發-中介軟體(Middleware)

要正確使用Middleware來構建自己的應該程式,需要理解Run,Use,Map,MapThen這四個方法是如何使用的, 下面Ricman將自己的理解與大家分享。

一、Run擴充方法

Run方法在說明上是這樣的:在管道的尾端增加一個Middleware;它是執行的最後一個Middleware。即它執行完就不再執行下一個Middleware了。如下程式碼範例。

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            var loger = loggerFactory.CreateLogger("TestLogger");                      //第一個Run 執行了            app.Run(async context =>            {                loger.LogInformation("run 1 start");                await context.Response.WriteAsync("hello world!,run 1");                loger.LogInformation("run 1 end");            });            //第二個Run 沒的執行            app.Run(async context =>            {                loger.LogInformation("run 2 start");                await context.Response.WriteAsync("hello world!,run 2");                loger.LogInformation("run 2 end");            });                    }

 

輸出的結果為:

只列印出了第一個Run中的內容。而程式也不會響應第二個Run方法中的內容。

 

二、Use擴充方法

Use方法,則是在管道中增加一個Middleware。如果調用了next.Invoke()方法,它會去執行下一個Middleware 。我們把上面的例子稍作修改:

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            var loger = loggerFactory.CreateLogger("TestLogger");                      //use 方法 執行了            app.Use (async (context,next) =>            {                loger.LogInformation("Use 1 start");                await context.Response.WriteAsync("hello world!,Use 1");                loger.LogInformation("Use 1 end");            });            //Run 方法沒的執行            app.Run(async context =>            {                loger.LogInformation("run 1 start");                await context.Response.WriteAsync("hello world!,run 1");                loger.LogInformation("run 1 end");            });                    }

 

輸出結果是什嗎?

沒有調用next.Invoke();尾端的Middleware即Run方法內沒有執行。使用Use方法,而沒有調用next.Invoke(),Use的效果與Run的效果是一致的。為了驗證Use 的效果,我們再修改代碼。

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            var loger = loggerFactory.CreateLogger("TestLogger");                      //執行了            app.Use (async (context,next) =>            {                loger.LogInformation("Use 1 start");                await context.Response.WriteAsync("hello world!,Use ");                await next.Invoke();                loger.LogInformation("Use 1 end");            });            //沒的執行            app.Run(async context =>            {                loger.LogInformation("run 1 start");                await context.Response.WriteAsync("  hello world!,run ");                loger.LogInformation("run 1 end");            });                    }

 

此時,輸入以下的結果

即Use與Run程式碼片段都被執行了。需要注意的是,管道中可以增加多個middleware,他們是按順序執行的,執行的順序與在Configure方法中代碼的順序是一致的。

 

三、Map與MapThen

Map比較不同,它將Middleware添加到管道中,它是在管道中增加了分枝。通過影射路徑的方式,增加管道分枝。我們保留上面例子,並增加代碼。如下:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            var loger = loggerFactory.CreateLogger("TestLogger");                      //執行了            app.Use (async (context,next) =>            {                loger.LogInformation("Use 1 start");                await context.Response.WriteAsync("hello world!,Use ");                await next.Invoke();                loger.LogInformation("Use 1 end");            });            app.Map("/mapTest", HandleMap);            //沒的執行            app.Run(async context =>            {                loger.LogInformation("run 1 start");                await context.Response.WriteAsync("  hello world!,run ");                loger.LogInformation("run 1 end");            });                    }        private static void HandleMap(IApplicationBuilder app)        {            app.Run(async context =>            {                await context.Response.WriteAsync("Hello ,that is Handle Map ");            });        }

 

運行起來,我們在瀏覽器中輸入” http://localhost:12716/mapTest” 得到的結果如下:

mapTest分枝被執行了。

MapThen就更有意思,從字面上感覺有點類似查詢的意思。對了。它就是處理合格Request去執行給定的方法。我們修改代碼

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            var loger = loggerFactory.CreateLogger("TestLogger");                      //執行了            app.Use (async (context,next) =>            {                loger.LogInformation("Use 1 start");                await context.Response.WriteAsync("hello world!,Use ");                await next.Invoke();                loger.LogInformation("Use 1 end");            });            app.MapWhen(context =>           {              return context.Request.Query.ContainsKey("q");            }, HandleQuery);            //沒的執行            app.Run(async context =>            {                loger.LogInformation("run 1 start");                await context.Response.WriteAsync("  hello world!,run ");                loger.LogInformation("run 1 end");            });                    }         private static void HandleQuery(IApplicationBuilder app)        {            app.Run(async context =>            {                   await context.Response.WriteAsync("  Hello ,this is Handle Query ");            });        }

 

我們要處理的是:如果有URL中的參數包含了q字母的話,就去執行HandleQuery方法。看一下結果

 

可以看出來,MapWhen可以處理很多的東西,比如我們要處理Request表頭中某特定的內容,可以使用MapWhen來處理。

 

如果你覺得本文對你有協助,請點擊“推薦”

 

dotnetCore增加MiddleWare的Run,Use Map MapThen四個擴充方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.