Owin Middleware Components(OMCs) 通過安裝Install-Package Microsoft.Owin.Host.SystemWeb 可以讓OMCs在IIS集成管道下工作 在IIS集成管道里,這個request pipeline 包含HttpModules關聯到一組預 ...
Owin Middleware Components(OMCs)
通過安裝Install-Package Microsoft.Owin.Host.SystemWeb
可以讓OMCs在IIS集成管道下工作
在IIS集成管道里,這個request pipeline 包含HttpModules關聯到一組預定義的管道事件,例如
BeginRequest, AuthenticateRequest, AuthorizeRequest,等
如果我們將OMC和HttpModule進行比較,OMC也和HttpModule一樣,必須要被註冊到一個恰當的預定義的管道事件里,比如下麵的這個Httpmodule,
當一個請求來到AuthenticateRequest階段時,MyModule
會被調用
public class MyModule : IHttpModule { public void Dispose() { //clean-up code here. } public void Init(HttpApplication context) { // An example of how you can handle AuthenticateRequest events. context.AuthenticateRequest += ctx_AuthRequest; } void ctx_AuthRequest(object sender, EventArgs e) { // Handle event. } }
為了使OMC取參與和HttpModule相同的基於事件的執行順序,Katana運行時代碼掃描Startup配置,並且把每個OMC關聯到某個集成管道事件里,
比如下麵的配置:
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using System.Web; using System.IO; using Microsoft.Owin.Extensions; [assembly: OwinStartup(typeof(owin2.Startup))] namespace owin2 { public class Startup { public void Configuration(IAppBuilder app) { app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "Middleware 1"); return next.Invoke(); }); app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "2nd MW"); return next.Invoke(); }); app.Run(context => { PrintCurrentIntegratedPipelineStage(context, "3rd MW"); return context.Response.WriteAsync("Hello world"); }); } private void PrintCurrentIntegratedPipelineStage(IOwinContext context, string msg) { var currentIntegratedpipelineStage = HttpContext.Current.CurrentNotification; context.Get<TextWriter>("host.TraceOutput").WriteLine( "Current IIS event: " + currentIntegratedpipelineStage + " Msg: " + msg); } } }
輸出如下:
Current IIS event: PreExecuteRequestHandler Msg: Middleware 1 Current IIS event: PreExecuteRequestHandler Msg: 2nd MW Current IIS event: PreExecuteRequestHandler Msg: 3rd MW
可以看到Katana運行時預設映射每個OMC到IIS管道事件PreRequestHandlerExecute
你可以根據需要調整這個OMC和管道事件的這種預設關係,具體使用一個擴展方法IAppBuilder UseStageMarker(),
像下麵這樣:
public void Configuration(IAppBuilder app) { app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "Middleware 1"); return next.Invoke(); }); app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "2nd MW"); return next.Invoke(); }); app.UseStageMarker(PipelineStage.Authenticate); app.Run(context => { PrintCurrentIntegratedPipelineStage(context, "3rd MW"); return context.Response.WriteAsync("Hello world"); }); app.UseStageMarker(PipelineStage.ResolveCache); }
輸出如下:
Current IIS event: AuthenticateRequest Msg: Middleware 1 Current IIS event: AuthenticateRequest Msg: 2nd MW Current IIS event: ResolveRequestCache Msg: 3rd MW
https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline