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 ({            "Http://localhost:52824/api/register",            "GET",            function  (data) {                Console.log ("JSON:" + data);            }        );

Post mode

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

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

        /// <summary>        ///HttpClient Implementing a GET Request/// </summary>        Static Async voidDooget () {stringURL ="http://localhost:52824/api/register?id=1&leval=5"; //Create httpclient (note incoming httpclienthandler)            varHandler =NewHttpclienthandler () {automaticdecompression =Decompressionmethods.gzip}; using(varHTTP =NewHttpClient (handler)) {                //await an asynchronous wait for a response                varResponse =awaithttp.                Getasync (URL); //ensure HTTP Success status valueResponse.                Ensuresuccessstatuscode (); //await asynchronously reads the last JSON (note that at this point the GZip has been automatically decompressed since automaticdecompression = decompressionmethods.gzip)Console.WriteLine (awaitResponse.            Content.readasstringasync ()); }        }

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

     /// <summary>        ///HttpClient Implementing a POST request/// </summary>        Static Async voidDoopost () {stringURL ="Http://localhost:52824/api/register"; varUserId ="1"; //set the automaticdecompression of Httpclienthandler            varHandler =NewHttpclienthandler () {automaticdecompression =Decompressionmethods.gzip}; //Create httpclient (note incoming httpclienthandler)            using(varHTTP =NewHttpClient (handler)) {                //use Formurlencodedcontent to do httpcontent                varContent =NewFormurlencodedcontent (Newdictionary<string,string>()                       {                  {"", userId}//the key name must be empty                 }); //await an asynchronous wait for a response                varResponse =awaithttp.                Postasync (URL, content); //ensure HTTP Success status valueResponse.                Ensuresuccessstatuscode (); //await asynchronously reads the last JSON (note that at this point the GZip has been automatically decompressed since automaticdecompression = decompressionmethods.gzip)Console.WriteLine (awaitResponse.            Content.readasstringasync ()); }        }

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

        /// <summary>        ///HttpClient Implementing a put request/// </summary>        Static Async voidDooput () {stringURL ="http://localhost:52824/api/register?userid="+userId; varUserId ="1"; //set the automaticdecompression of Httpclienthandler            varHandler =NewHttpclienthandler () {automaticdecompression =Decompressionmethods.gzip}; //Create httpclient (note incoming httpclienthandler)            using(varHTTP =NewHttpClient (handler)) {                //use Formurlencodedcontent to do httpcontent                varContent =NewFormurlencodedcontent (Newdictionary<string,string>()                       {                   {"","Data"}//the key name must be empty                }); //await an asynchronous wait for a response                varResponse =awaithttp.                Putasync (URL, content); //ensure HTTP Success status valueResponse.                Ensuresuccessstatuscode (); //await asynchronously reads the last JSON (note that at this point the GZip has been automatically decompressed since automaticdecompression = decompressionmethods.gzip)Console.WriteLine (awaitResponse.            Content.readasstringasync ()); }        }

OK, here, our client how to call the Web API is finished, in fact, the phone side, the tablet side is also related to the way to call, they also have their own httpclient class, similar!

WEBAPI Series ~ Invoking the 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.