ASP. NET Web API Practice Series (ii) Get/post method call Web API

Source: Internet
Author: User

This article gives a get/post way to access the Web API, which is similar to the post call for the Put/delete method.

One, the Web API call helper Class

The following is the code for the Web API call helper class:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Net.Http;4 usingSystem.Net.Http.Headers;5 usingSystem.Text;6 usingsystem.web;7 8 namespaceTestapi9 {Ten     /// <summary> One     ///Webapi accessing Help classes A     /// </summary> -      Public classWebapihepler -     { the         /// <summary> -         ///Generate final URL -         /// </summary> -         /// <param name= "BaseUrl" >base URL (without query string)</param> +         /// <param name= "Dictparam" >Query parameter Dictionary</param> -         /// <returns>Final URL</returns> +         Private Static stringGetlasturl (stringBASEURL, dictionary<string,string>Dictparam) A         { at             varSburl =NewStringBuilder (BASEURL); -             if(Dictparam! =NULL&& Dictparam.count >0) -             { -Sburl.append ("?"); -                 intindex =0; -                 foreach(varIteminchDictparam) in                 { -Sburl.append (string. Format ("{0}={1}", item. Key, to Httputility.urlencode (item. Value, Encoding.UTF8 )); +                     if(Index < Dictparam.count-1) -                     { theSburl.append ("&"); *                     } $index++;Panax Notoginseng                 } -             } the             varURL =sburl.tostring (); +             returnURL; A         } the  +         /// <summary> -         ///Get method call Web Api $         /// </summary> $         /// <param name= "BaseUrl" >base URL (without query string)</param> -         /// <param name= "Dictparam" >Query parameter Dictionary</param> -         /// <param name= "Result" >return Data (JSON format)</param> the         /// <param name= "ErrMsg" >error Message</param> -         /// <returns>success or not</returns>Wuyi          Public Static BOOLGet (stringBASEURL, dictionary<string,string> Dictparam, out stringResult out stringerrmsg) the         { -ErrMsg =string. Empty; Wuresult =string. Empty; -             Try About             { $                 using(varClient =NewHttpClient ()) -                 { -Client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (NewMediatypewithqualityheadervalue ("Application/json")); -                     varURL =Getlasturl (BASEURL, dictparam); A                     varTmpresult =client. Getasync (URL). Result; + Tmpresult.ensuresuccessstatuscode (); theresult =TmpResult.Content.ReadAsStringAsync (). Result; -                     return true; $                 } the             } the             Catch(Exception ex) the             { theErrMsg =Ex. Message; -                 return false; in             } the              the         } About  the         /// <summary> the         ///The Post method calls the Web Api the         /// </summary> +         /// <param name= "BaseUrl" >base URL (without query string)</param> -         /// <param name= "Dictparam" >Query parameter Dictionary</param> the         /// <param name= "Parsedata" >passing Entity Data (JSON format)</param>Bayi         /// <param name= "Result" >return Data (JSON format)</param> the         /// <param name= "ErrMsg" >error Message</param> the         /// <returns>success or not</returns> -          Public Static BOOLPost (stringBASEURL, dictionary<string,string> Dictparam,stringParsedata, out stringResult out stringerrmsg) -         { theErrMsg =string. Empty; theresult =string. Empty; the             Try the             { -                 using(varClient =NewHttpClient ()) the                 { theClient. DEFAULTREQUESTHEADERS.ACCEPT.ADD (NewMediatypewithqualityheadervalue ("Application/json")); the                     varURL =Getlasturl (BASEURL, dictparam);94                     varContent =Newstringcontent (Parsedata, Encoding.UTF8); theContent. Headers.contenttype =NewMediatypeheadervalue ("Application/json"); the                     varTmpresult =client. Postasync (URL, content). Result; the Tmpresult.ensuresuccessstatuscode ();98result =TmpResult.Content.ReadAsStringAsync (). Result; About                     return true; -                 }101             }102             Catch(Exception ex)103             {104ErrMsg =Ex. Message; the                 return false;106             }107         }108     }109}
Ii. part of the explanation

Make a partial description of the above code:

    • The Getlasturl method is used to obtain the final URL based on the base URL and query parameter dictionary
    • Client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (new Mediatypewithqualityheadervalue ("application/json")); This code indicates that you want the service to return a JSON string.
    • Content. Headers.contenttype = New Mediatypeheadervalue ("application/json"); Represents the delivery of entity content in JSON format.

ASP. NET Web API Practice Series (ii) Get/post method call Web API

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.