標籤:exception policy sse esc wiki font rpo 傳遞 size
上一節我們講述全域配置。本節將講述全域配置的DefaultServer,它是一個HttpServer類型。 主要作用就是接受每一次請求,然後分發給訊息處理常式鏈依次處理。從HttpServer定義可以看出,其本質是一個訊息處理常式,其繼承於DelegatingHandler。從其代碼定義如下:
//參數為
public HttpServer(HttpConfiguration configuration, HttpMessageHandler dispatcher);
// 摘要:
// 擷取用於配置此執行個體的 System.Web.Http.HttpConfiguration。
//
// 返回結果:
// 用於配置此執行個體的 System.Web.Http.HttpConfiguration。
public HttpConfiguration Configuration { get; }
//
// 摘要:
// 擷取用於處理傳入請求的 HTTP 發送器。
//
// 返回結果:
// 用於處理傳入請求的 HTTP 發送器。
public HttpMessageHandler Dispatcher { get; }
公開兩個唯讀屬性。
Dispatcher :承擔分發中介者,實際上一個 HttpRoutingDispatcher類型。我們回顧一下上一節部分代碼:
//以下都使用消極式載入。
private static Lazy<HttpConfiguration> _configuration = CreateConfiguration();
private static Lazy<HttpMessageHandler> _defaultHandler = CreateDefaultHandler();
private static Lazy<HttpServer> _defaultServer = CreateDefaultServer();
private static Lazy<HttpConfiguration> CreateConfiguration()
{
return new Lazy<HttpConfiguration>(() =>
{
HttpConfiguration config = new HttpConfiguration(new HostedHttpRouteCollection(RouteTable.Routes));
ServicesContainer services = config.Services;
Contract.Assert(services != null);
services.Replace(typeof(IAssembliesResolver), new WebHostAssembliesResolver());
services.Replace(typeof(IHttpControllerTypeResolver), new WebHostHttpControllerTypeResolver());
services.Replace(typeof(IHostBufferPolicySelector), new WebHostBufferPolicySelector());
services.Replace(typeof(IExceptionHandler),
new WebHostExceptionHandler(services.GetExceptionHandler()));
return config;
});
}
//預設的訊息處理常式,實際就是路由分發器
private static Lazy<HttpMessageHandler> CreateDefaultHandler()
{
return new Lazy<HttpMessageHandler>(() => new HttpRoutingDispatcher(_configuration.Value));
}
//這裡傳遞的是路由分發器。
private static Lazy<HttpServer> CreateDefaultServer()
{
return new Lazy<HttpServer>(() => new HttpServer(_configuration.Value, _defaultHandler.Value));
}
以上代碼實現了HttpServer的初始化工作。同時他重寫了 InnerHandler屬性。內部的實現機制是:
將訊息處理常式鏈順序倒置,依次設定訊息處理常式。這樣就實現了訊息處理常式,先入先出的原理:例如
config.MessageHandlers.Add(new M2DelegatingHandler());
config.MessageHandlers.Add(new M1DelegatingHandler());
則是先調用M2DelegatingHandler,然後在調用M1DelegatingHandler,再次調用HttpRoutingDispatcher,最後將委託分發給HttpControllerDispatcher
從上面可以看出HttpServer,大部分工作就是協調作用,分發作用。
有興趣的朋友可以下載web Api 源碼查看。http://aspnetwebstack.codeplex.com/wikipage?title=Contributors.
Web API源碼剖析之HttpServer