The previous article describes how to get an entity object from an input stream. This article describes passing parameters in the form of URLs. Simple parameters are no longer mentioned here, the main implementation of the shape as (string Name,woman Woman) such a parameter pass.
This and the following chapters are related to JS calls and C # calls, and the length of the long, please forgive us.
One, JS call.
WEBAPI:
Public classValuescontroller:apicontroller {[HttpPost] Public stringGetData (stringName,woman Woman) { return "I was"+ name +", I like"+woman. Name; } [HttpPost] Public stringGetData (Woman Woman) {returnWoman. Age +"of the"+woman. Name; } } Public classWoman//Just for demonstration convenience { Public stringname{Get;Set;} Public stringage{Get;Set;} }
View Code
JS end. JS End of the Obj2url (object generation key value pair) Implementation method is ugly, if there is a better way to please enlighten us.
varWoman = {Name: ' Liu Yifei ', age:18 }; functionObj2url (obj) {varResult= "; for(varIinchobj) {Result+ = i + "=" + obj[i]+ "&"; } returnResult.substr (0, result.length-1);//back to Name= Liu Yifei &age=18 } $(function () { $(' #btn '). Click (function() {$.ajax ({type:"POST", URL:"Http://localhost:7601/api/values/GetData?name= Landlord", Data:obj2url (woman), success:function(r) {alert (R); } }); }); });
View Code
If you are performing a form submission, you can directly take advantage of JQ's $ (' #formID '). Serialize () gets the key-value pair directly.
Look at the request data:
Execution Result:
Here are two points to note:
1, browser-initiated request, in addition to the URL-_. All non-alphanumeric characters are replaced with a percent (%) followed by a two-digit hexadecimal number, which is automatically urlencode.
2, the Request form Data, not encoded, can also be correctly passed to the API. (such as: Name: Liu Yifei?/)
This was tested, and the theoretical basis was not found. Is the conclusion correct? I forgot the friend's generous comment.
Second, C # calls. The main concern here
The service-side WEBAPI code does not change. Add a property to the woman class, public list<datetime> exercisetime {get; set;} to increase the difficulty.
Client:
First, the basic invocation class: This class is initiated with HttpWebRequest, is synchronous, later we will upgrade to HttpClient, asynchronous.
//PostService.cs Public classPostservice { Public BOOLPostwebrequest (stringPostURL,stringPostvalue, out stringreturnvalue) {returnvalue=string. Empty; Try { byte[] Bytedata =Encoding.UTF8.GetBytes (Postvalue); Uri URI=NewUri (PostURL); HttpWebRequest Webreq=(HttpWebRequest) webrequest.create (URI); Webreq.method="POST"; Webreq.contenttype="application/x-www-form-urlencoded"; Webreq.contentlength=bytedata.length; //Define stream InformationStream stream =Webreq.getrequeststream (); Stream. Write (Bytedata,0, bytedata.length); Stream. Close (); //Get return informationHttpWebResponse response =(HttpWebResponse) webreq.getresponse (); StreamReader StreamReader=NewStreamReader (response. GetResponseStream (), Encoding.UTF8); ReturnValue=Streamreader.readtoend (); //Close InformationStreamreader.close (); Response. Close (); Stream. Close (); return true; } Catch(Exception ex) {returnvalue=Ex. Message; return false; } } }
View Code
Specific calling code:
Private voidBtnpost_click (Objectsender, EventArgs e) {NameValueCollection queryString= System.Web.HttpUtility.ParseQueryString (string. Empty); querystring["Name"] ="Liu Yifei"; querystring[" Age"] =" -"; querystring["Exercisetime[0]"] =DateTime.Now.ToString (); querystring["Exercisetime[1]"] = DateTime.Now.AddHours (- A). ToString (); querystring["Exercisetime[2]"] ="haha"; stringPostData = Querystring.tostring ();//Returns "Key1=value1&key2=value2", all url-encoded//string postdata = "Name= Liu Yifei &age=18";//string postdata = "Name= Liu Yifei/&age=18"; ok. stringURL ="http://localhost:7601/api/values/GetData?name= landlord"; stringRetValue =""; Postservice Service=NewPostservice (); Service. Postwebrequest (URL, postdata, outRetValue); MessageBox.Show (RetValue); }
View Code
Call Result:
The passed-in name is the encoded value and needs to be decoded to get the correct value. It's kind of weird.
OK, let's do another experiment:
The calling code modifies the direct spelling string without encoding:
string postdata = " name= Liu Yifei &age=18 " ;//string postdata = "Name= Liu Yifei?/&age=18"; OK. string url = " http://localhost:7601/api/values/getdata?name= landlord " ; string retvalue = "" ; Postservice service = new Postservice (); Service. Postwebrequest (URL, postdata, out RetValue);
Conclusion: The request data initiated by the client needs to be encoded and decoded for pairing.
The foundation is poor, it shows. Principle, principle, principle, say three times. Forget to know the staff friends to enlighten.
Note 1, list<t> of the method of transmission. 2. The property of the class is the case of the entity class, for example:
Public classWoman//Just for demonstration convenience { Public stringname{Get;Set;} Public stringage{Get;Set;} PublicList<datetime> Exercisetime {Get;Set; } PublicSon son {Get;Set; } } Public classSon { Public stringname{Get;Set;} Public intage{Get;Set;} }
View Code
Then the conjecture is delivered by:
querystring["son.name " " son "; querystring["son.age" "2";
A little more complicated, there are several sons:
Public Get set; }
Then the conjecture is delivered by:
querystring["son[0". Name"" son "; querystring["son[0". Age""2";
Please verify it by yourself.
Webapi Biography (iii)