WEBAPI Series ~ Invoking the Web API interface via HttpClient

Source: Internet
Author: User

HttpClient is a encapsulated class, mainly used for HTTP communication, it is implemented in. Net,java,oc, of course, I will only. NET, so, only speak. NET HttpClient to invoke the Web API method, based on the specificity of the API project, It needs to have a completely secure environment, so your API controller looks a bit special, only 5 methods, and all the standard HTTP method, I think this design is very good, very clear, and in order to achieve security, it does not support the use of traditional form data, instead of the Frombody parameter, It refers to taking httprequestmessage parameters, not all request data, which is based on security considerations.

The standard of an API interface parameter

Get mode, can have multiple overloads, have multiple parameters

Post method, can have only one parameter, and with [frombody] constraints, if there are more than one parameter, need to be passed as an object

Put, there can only be two parameters, one of which is passed by Request.QueryString way, as the primary key to update the object, not one is the [frombody] field, is also a field, if more than one field needs to encapsulate it as an object

Standard interface

Two callers, the standard of the parameter

When the client makes the interface call, we take the Web page as an example to look at the code for the Ajax cross-domain request on the web side.

Get mode

$.ajax ({            URL: "Http://localhost:52824/api/register",            Type: "GET",            success:function (data) {                Console.log ("JSON:" + data);            }        );

Post mode

  $.ajax ({            URL: "Http://localhost:52824/api/register",            Type: "POST",            data: {': ' 1 '},//here the key name must be empty, Multiple parameters to pass the object, API side parameter name must be value            success:function (data) {                Console.log ("Post:" + data);            }        );

Three get interface data in the console (only asynchronous implementation)

      <summary>        //httpclient implement GET request        ///</summary> static async void Dooget ()        {            String url = "Http://localhost:52824/api/register?id=1&leval=5";            Create httpclient (note incoming httpclienthandler)            var handler = new Httpclienthandler () {automaticdecompression = Decompressionmethods.gzip};            The using (var http = new HttpClient (handler))            {                //await asynchronously waits for the response                var response = await http. Getasync (URL);                Ensure that the HTTP success status value is                response. Ensuresuccessstatuscode ();                Await asynchronously reads the last JSON (note that at this point the GZip has been automatically decompressed since automaticdecompression = decompressionmethods.gzip)                Console.WriteLine (await response. Content.readasstringasync ());            }        }

Four implement post in the console submit data (only asynchronous implementations)

     <summary>//HttpClient implement POST request///</summary> static async void Doopost ()            {String url = "Http://localhost:52824/api/register";            var userId = "1"; Set Httpclienthandler automaticdecompression var handler = new Httpclienthandler () {automaticdecompression = D            Ecompressionmethods.gzip}; Create HttpClient (note incoming httpclienthandler) using (var http = new HttpClient (handler)) {// Use Formurlencodedcontent to do httpcontent var content = new Formurlencodedcontent (new dictionary<string, Strin                G> () {"", userid}//Key name must be empty}); Await async wait response var response = await http.                Postasync (URL, content); Ensure that the HTTP success status value is response.                Ensuresuccessstatuscode (); Await asynchronously reads the last JSON (note that at this point the gzip is automatically decompressed because the automaticdecompression = DecompressionmethoDs. GZIP) Console.WriteLine (await response.            Content.readasstringasync ()); }        }

Five implement put to submit data in the console (asynchronous implementation only)

        <summary>//HttpClient implement put request///</summary> static async void Dooput ()            {String url = "http://localhost:52824/api/register?userid=" + userid;            var userId = "1"; Set Httpclienthandler automaticdecompression var handler = new Httpclienthandler () {automaticdecompression = D            Ecompressionmethods.gzip}; Create HttpClient (note incoming httpclienthandler) using (var http = new HttpClient (handler)) {// Use Formurlencodedcontent to do httpcontent var content = new Formurlencodedcontent (new dictionary<string, Strin                G> () {"", "Data"}//key name must be empty}); Await async wait response var response = await http.                Putasync (URL, content); Ensure that the HTTP success status value is response.                Ensuresuccessstatuscode (); Await asynchronously reads the last JSON (note that at this point gzip is automatically decompressed because the automaticdecompression = Dec aboveOmpressionmethods.gzip) Console.WriteLine (await response.            Content.readasstringasync ()); }        }

Webapi Series ~ Invoke Web API interface via HttpClient

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.