The previous session described how to use httpclient to invoke a standard Web API interface, and we know that the Post,put method can have only one frombody parameter, and then there are multiple parameters, it is mentioned that it needs to be encapsulated into an object to be passed, And this is mainly around this topic, the interface layer to add a new class User_info for data transfer, and the client using the Web Ajax and console httpclient the way to implement separately, follow me!
The following defines a complex type object
Public class User_info { publicintgetset;} Public string Get Set ; } Public string Get Set ; } }
Modify the last API section below to let it manipulate the object
[Corsattribute ("http://localhost:3321")] Public classRegistercontroller:apicontroller { Public StaticList<user_info> Model =NewList<user_info>() { NewUser_info{id=1, name="Zzl", info="Zzl is the landlord"}, NewUser_info{id=2, name="zhz", info="Zhz is Zzl's son."}, NewUser_info{id=3, name="ZQL", info="Zql is Zzl's wife."}, NewUser_info{id=4, name="Bobo", info="Bobo is Zzl's friend."} }; //GET api/values PublicIenumerable<user_info>Get () {returnModel; } //GET API/VALUES/5 PublicUser_info Get (intID) {varentity = Model.firstordefault (i = i.id = =ID); returnentity; } //GET api/values/5?leval=1 PublicHttpresponsemessage Get (intIdintleval) { return NewHttpresponsemessage (Httpstatuscode.ok) {Content=NewStringcontent ("<em style= ' color:red ' > Successful response (id,level) </em>", System.Text.Encoding.UTF8,"text/html") }; } //POST api/values Publichttpresponsemessage Post ([frombody]user_info value) {Model.add (NewUser_info {Id=value. Id, Info=value. Info, Name=value. Name,}); //User Login Related return NewHttpresponsemessage (Httpstatuscode.ok) {Content=NewStringcontent ("Add data success, User ID:"+ value. Id, System.Text.Encoding.UTF8,"Text/plain") }; } //PUT api/values?userid=5 PublicHttpresponsemessage Put (intuserid, [Frombody]user_info value] { varentity = Model.firstordefault (i = i.id = =userid); Entity. Info=value. Info; Entity. Name=value. Name; return NewHttpresponsemessage (Httpstatuscode.ok) {Content=NewStringcontent ("Modify data success, PRIMARY key:"+ userid +", object:"+value. Name)}; } //DELETE API/VALUES/5 PublicHttpresponsemessage Delete (intID) {model.remove (Model.firstordefault (i= = I.id = =id)); return NewHttpresponsemessage (Httpstatuscode.ok) {Content=NewStringcontent ("Delete Data successfully") }; }
And the most critical place is at the time of each client invocation, first of all, you can't expect the client to reference your assembly, because the platform cannot implement such a reference (Java & C#,js & c#,php & C #), so you need to have their own method at the time of invocation, And JS Ajax call, directly using the JSON object, the key name object
Entity properties, when using HttpClient, directly assign a set of key-value pairs to the Formurlencodedcontent object, as described below
The JS implementation of HTML
$.ajax ({URL:"Http://localhost:52824/api/register", type:"POST", data: {Id:5, Name: ' New ', Info: ' Everybody's Good '},//here the key name must be empty, multiple parameters please pass the object, API side parameter name must be valueSuccessfunction(data) {Console.log ("Post:" +data); } }); $.ajax ({URL:"Http://localhost:52824/api/register", type:"GET", Success:function(data) { for(varIinchdata) {Console.log (Data[i]. Id+ " " +Data[i]. Name); } } });
Results
Implementation using HttpClient objects in the console program
///<summary> ///HttpClient Implementing a POST request ///</summary>Static AsyncvoidDoopost () {string URL= "Http://localhost:52824/api/register"; //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>() { {"Id", "6"}, {"Name", "Add Zzl"}, {"Info", "Add Action"}//the key name must be empty }); //await an asynchronous wait for a response varResponse =await http. 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 (await response. Content.readasstringasync ()); } } ///<summary> ///httpclient Implement GET request ///</summary>Static AsyncvoidDooget () {string URL= "Http://localhost:52824/api/register?id=1"; //Create httpclient (note incoming httpclienthandler) varHandler =NewHttpclienthandler () {automaticdecompression =Decompressionmethods.gzip}; using (varHTTP =NewHttpClient (handler)) { //await an asynchronous wait for a response varResponse =await http. 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 (await response. Content.readasstringasync ()); } } ///<summary> ///httpclient Implement put request ///</summary>Static AsyncvoidDooput () {varUserId = 1; String URL= "Http://localhost:52824/api/register?userid=" +userId; //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>() { {"Name", "Modify Zzl"}, {"Info", "put Modify action"}//the key name must be empty }); //await an asynchronous wait for a response varResponse =await http. 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 (await response. Content.readasstringasync ()); } }
WEBAPI Series ~ Call the Web API interface through the HttpClient ~ Cont ~ the delivery of entity parameters