Service Interface
Interface 1:
// Post: Http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest1 [HttpPost] Public httpresponsemessage FunctionTest1 (Model1 model) { ... }
Interface 2:
// Post: Http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest2 [HttpPost] Public httpresponsemessage FunctionTest2 (Model2 model) { ... }
Interface parameters:
Public classmodel1{ PublicList<model2> List1 {Get;Set; } Public stringName {Get;Set; }} Public classmodel2{ Public stringfield21{Get;Set;} Public stringfield22{Get;Set;}}
Client Calls
for Interface 1: Using Stringcontent, the transmitted data is serialized and written to the body of the request message.
varM1 =New{List1 =Newlist<Object> {New{Field21 ="Field21", Field22 ="Field21"},New{Field21 ="Field21", Field22 ="Field21"}}, Name ="Tests" }; Httpcontent content=NewStringcontent (Jsonconvert.serializeobject (M1)), content. Headers.contenttype=NewMediatypeheadervalue ("Application/json"); HttpClient Client=NewHttpClient ();using(Httprequestmessage request =NewHttprequestmessage (Httpmethod.post,@"Http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest1") {request. Content=content; Httpresponsemessage Response=client. SendAsync (Request). Result; varR = Response. content.readasasync<Object>(); R.wait (); vars =r.result.tostring ();}
If you use formurlencodedcontent is not successful.
There are two ways to call an interface 2 to pass a parameter
The first method: the use of Formurlencodedcontent writes the request input to the body of the message
Httpcontent content =NewFormurlencodedcontent (Newdictionary<string,string>() {{"Field21","Field21"}, {"Field22","Field22"}}); HttpClient Client=NewHttpClient ();using(Httprequestmessage request =NewHttprequestmessage (Httpmethod.post,@"Http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2") {request. Content=content; Httpresponsemessage Response=client. SendAsync (Request). Result; varR = Response. content.readasasync<Object>(); R.wait ();}
The second method: Adopt stringcontent write request data to the body of the message
varModel =New{Field21 ="Field21", Field22 ="Field22" }; Httpcontent content=Newstringcontent (Jsonconvert.serializeobject (model)), content. Headers.contenttype=NewMediatypeheadervalue ("Application/json"); HttpClient Client=NewHttpClient ();using(Httprequestmessage request =NewHttprequestmessage (Httpmethod.post,@"Http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2") {request. Content=content; Httpresponsemessage Response=client. SendAsync (Request). Result; varR = Response. content.readasasync<Object>(); R.wait ();}
ASP. NET Web API client calls