Learn the "HTTP method rewrite" of the ASP. NET WEB API framework

Source: Internet
Author: User

Recently looking at old A's "ASP. NET Web API Framework", this book for me at this stage is still more appropriate (for the call is already more familiar with the development of the project, but did not deeply understand how many of the content can be "called"). See the fourth chapter, some content to see although can understand, but did not encounter specific problems, it seems there is no sense of enlightened. At the same time, some of the content is "This is dry" at a glance, may have encountered some problems before, at that time with some rubbing solution, but now see the example in the book unsanitary environment. So, just pick out the individual can be carried out and immediately be able to apply the content in the project to share the exchange with you. It will be interspersed with some knowledge points in the framework. Inappropriate, please advise. Thank you very much.

Cause: The ideal RESTful Web API takes a resource-oriented architecture and uses the requested HTTP method to represent the type of operation against the target resource, but the ideal and the reality are at a distance. Although the HTTP protocol provides a series of native HTTP methods, many are not supported in a specific network environment. Like what:

1, some browsers can only send get and POS requests, the client sends a PUT request can not necessarily be understood by the server.
2, in addition to the client and server restrictions on the HTTP method used by the request, such as proxy, gateway, etc. these intermediate parts have restrictions on the HTTP method

How to fix it, we generally use "HTTP method rewrite" to solve this problem. This example customizes the HTTP method override for Httpmessagehandler, which is intended to replace the requested HTTP method.

The steps are as follows:

  Create a new empty ASP. NET Web API app, creating a Democontroller

    This is not much to say, directly put a code.

Defines the interface for different HTTP methods, and returns the corresponding HTTP method name, which makes it easier to determine which HTTP method to use for a specific request, after sending the request below, by its return value.

1  Public classDemocontroller:apicontroller2     {3          Public stringGet ()4         {5             return "Get";6         }7 8          Public stringPost ()9         {Ten             return "Post"; One         } A  -          Public stringPut () -         { the             return "Put"; -         } -  -          Public stringDelete () +         { -             return "Delete"; +         } A  at}

Second, create a Httpmessagehandler implementation of the HTTP method overlay, registered in the Web API message processing pipeline

    This has a noun, pipe, what do you mean? This is defined in the book, the core framework of the ASP. NET Web API is a message processing pipeline, which is an ordered combination of a set of Httpmessagehandler. This is a duplex pipeline, where the request message flows from one end to the next and passes through all httpmessagehandler processing. At the other end, the target httpcontroller is activated, the action method is executed, and the response message is generated.

 

At first glance, a little confused, do not know my own foundation is not enough or why, a pile of text down, I will faint, but fortunately there is code, read the code, look at the text, understand, more comfortable.

The above paragraph, in my current understanding, is: Why do you hit a uri,asp.net Web API to find the corresponding action execution and return it, in fact, the browser (client) initiated the request to the action execution of the process through a series of actions, This sequence of operations is separated into categories, each of which can be seen as a separate existence, called a httpmessagehandler, and multiple Httpmessagehandler constitute the so-called pipeline. You can first interpret it as a bunch of filters.

Again, the Httpmessagehandlerthat we're going to create is to override the HTTP method. Once we've created it, we'll add it to the message-processing pipeline of the Web API so that our request comes after our custom Httpmessagehandler "Review".

Realize:

1, the new Httpmessagehandler, the overriding method SendAsync, the key is actually the request in the head of the Key-value "X-http-method-override" out of the request itself to cover the HTTP method, Why do you call that name? Conventional, or called--rules?

(If a friend of mine on a channel might have noticed, there is a question about how to set the value of "X-http-method-override", which will be 0 0 later)

 Public classHttpmethodoverridehandler:delegatinghandler {protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {IEnumerable<string>Methodoverrideheader; if(Request. Headers.trygetvalues ("X-http-method-override", outMethodoverrideheader)) {                //this replaces the request's own HTTP method with the method defined in "X-http-method-override".Request. Method =NewHttpMethod (Methodoverrideheader.first ()); }            return Base.        SendAsync (Request, CancellationToken); }    }

The Delegatinghandler here is inherited from Httpmessagehandler

2, Httpmessagehandler is established, it is to be added to the pipeline

Quite simply, add the following line of code to the Application_Start () in our Global.asax.cs

GLOBALCONFIGURATION.CONFIGURATION.MESSAGEHANDLERS.ADD (new Httpmethodoverridehandler ());

    

At this point, the service end of the work finished. We are already in an empty ASP. NET Web The API project adds an accessible Democontroller and creates a Httpmessagehandler for HTTP method overrides (by getting the x-http-method-override of the request header to overwrite the HTTP method) and joins the Web The message processing pipeline for the API. Next is the client impersonation call.

Iii. creating a Client for access testing

For the client, it is not required by itself, it can be called by the Web page browser, or it can write a winform,wpf. Here is the console for example, the book is also the console, later I will also use the Web page JS to invoke, after all, this is the norm of our work.

1. Create a new empty console application layer program

Direct Sticker Code Program.cs

Four requests were created, 1 and 2 of the request headers were not set x-http-method-override, 1 had its own HTTP method set to get, and the other three were post.

1 class Program2     {3        4         Static voidMain (string[] args)5         {6HttpClient httpClient1 =NewHttpClient ();7HttpClient HttpClient2 =NewHttpClient ();8HttpClient HttpClient3 =NewHttpClient ();9HttpClient httpClient4 =NewHttpClient ();Ten  OneHTTPCLIENT3.DEFAULTREQUESTHEADERS.ADD ("X-http-method-override","PUT"); AHTTPCLIENT4.DEFAULTREQUESTHEADERS.ADD ("X-http-method-override","DELETE"); -  -Console.WriteLine ("{0,-7}{1,-24}{2,-12}{3,-24}","Method","X-http-method-override","Action","The first several requests"); the  -Invokewebapi (HttpClient1, Httpmethod.get,1); -Invokewebapi (HttpClient2, Httpmethod.post,2); -Invokewebapi (HttpClient3, Httpmethod.post,3); +Invokewebapi (HttpClient4, Httpmethod.post,4); -  + Console.read (); A         } at  -         Async Static voidInvokewebapi (HttpClient HttpClient, HttpMethod method,intrequesttime) -         { -             stringRequestUri ="Http://localhost:52697/api/demo";//The address of the Web API project created above -Httprequestmessage request =NewHttprequestmessage (method, RequestUri); -Httpresponsemessage response =awaitHttpclient.sendasync (request); inienumerable<string>methodsoverride; -  toHttpClient.DefaultRequestHeaders.TryGetValues ("X-http-method-override", outmethodsoverride); +             stringActionName =Response. Content.readasstringasync (). Result; -             stringMethodoverride = Methodsoverride = =NULL?"N /A": Methodsoverride.first (); theConsole.WriteLine ("{0,-7}{1,-24}{2,-12}{3,-24}", method, Methodoverride, Actionname.trim ('"'), requesttime); *         } $}

The code is very simple, according to what we said earlier, the output does not have a problem, should be set up the X-http-method-override request, its own HTTP request method will be in the request header x-http-method-override corresponding value to overwrite. Therefore, the following output results are obtained:

    

The HTTP methods of the 3rd and 4 requests were "rewritten". The task is complete.

Some students to ask questions, then we use JS to launch Ajax request when how to operate it, the key is actually how Ajax operation request header. Here is also an example

Add an HTML page to the Web API project above (here with jquery to manipulate Ajax) to add the code as follows:

    

If not unexpectedly, according to our idea, should be pop-up "PUT" instead of "POST", then the fact?

Bingo~~ sleep! Haven't updated the blog park for a long time, not lazy.

Learn the "HTTP method rewrite" of the ASP. NET WEB API framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.