Httpmessagehandler Pipe
In the Web API, Microsoft has implemented a pipeline design----httpmessagehander (in fact, WCF has a similar architecture) for better architecture expansion.
The heads and tails in the entire pipeline are Httpserver, Httproutingdispatcher, and they all inherit Httpmessagehandler, where ASP. NET provides us with an extensible delegatinghandler, Let's take a look at a couple of classes before the relationship.
SendAsync is the method that handles the request. In Delegatinghandler, there is a property innerhandler of type Httpmessagehandler. It is the key to forming a pipeline. Because of this property, the Delegatinghandler are able to cascade together and step through each delegatinghandler in the pipeline.
In Httpserver there are two newly added properties of the configuration with dispatcher, where dispatcher points to the end of the pipe httproutingdispatcher. In httpconfiguration there is a type of collection< Delegatinghandler> 's Properties Messagehandlers, we add custom Delegatinghandler to this collection to add to the entire pipeline. So we can see the whole Httpmessaghandler pipeline that is basically defined in Httpserver.
Here we define a post and put that can be requested (of course this is just an example)
public class Httpmethodchangehandler:delegatinghandler { protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync (httprequestmessage request, System.Threading.CancellationToken CancellationToken) { var method = Request. Method; if (Request. Method = = httpmethod.post) { request. Method = Httpmethod.put; } else if (request. Method = = httpmethod.put) { request. Method = Httpmethod.post; } Return base. SendAsync (Request, CancellationToken); } }
We add the following statement in the Httpapplication.application_start
Globalconfiguration.configure (t = t.messagehandlers.add (new Httpmethodchangehandler ()));
Defines the Put,post method in Democontroller
[HttpPost] public string post () { Return "This is a post method"; } [Httpput] public string put () { Return "This is a put method"; }
Here are the four test results:
Url:http://localhost:41666/api/demo/put Method:post
结果:"这是一个Put方法"
Url:http://localhost:41666/api/demo/put Method:put
结果:{"Message":"请求的资源不支持 http 方法"POST"。"}
Url:http://localhost:41666/api/demo/post Method:put
结果:"这是一个Post方法"
Url:http://localhost:41666/api/demo/post Method:post
结果:{"Message":"请求的资源不支持 http 方法"PUT"。"}
另外我们再在DemoController定义一个获取自定义DelegatingHandler的方法GetChains
Public ienumerable<string> getchains () { ienumerable<string> result = Getchains ( Globalconfiguration.defaultserver); return result; } Private ienumerable<string> Getchains (Delegatinghandler handler) { yield return handler. GetType (). FullName; var Innerhander = handler. Innerhandler as Delegatinghandler; if (Innerhander! = null) { yield return innerhander.gettype (). FullName; } }
ASP. WebAPI Httpmessagehandler Pipeline