WebApi Interface Passwords No longer Confused: Passwords Detailed

Posted by sryder on Thu, 13 Jun 2019 18:17:21 +0200

WebApi

Catalog (?)[-]

  1. A get request
    1. Base type parameters
    2. Entities as parameters
    3. Array as parameter
    4. Strange get request
      1. 1WebApi method name starts with get
      2. 2WebApi method name does not start with get
  2. Two post requests
    1. Base type parameters
      1. 1 Wrong Writing
      2. 1 Wrong Writing
      3. 2 correct usage
      4. 3 Recommended usage
  3. Tri put Request
    1. Base type parameters
    2. Entities as parameters
    3. Array as parameter
  4. Four delete requests
  5. 5 Summary


1. get request

Get requests are the ones we use most for fetching data.Here are a few examples of our get request parameter delivery.

1. Basic type parameters

  1. [HttpGet]  
  2. public string GetAllChargingData(int id, string name)  
  3. {  
  4.     return "ChargingData" + id;  
  5. }  
  1. $.ajax({  
  2.         type: "get",  
  3.         url: "http://localhost:27221/api/Charging/GetAllChargingData",  
  4.         data: { id: 1, name: "Jim", bir: "1988-09-11"},  
  5.         success: function (data, status) {  
  6.             if (status == "success") {  
  7.                 $("#div_test").html(data);  
  8.             }  
  9.         }  
  10.     });  
This is the most basic way to pass parameters for get requests, and there's nothing particularly interesting to say.

2. Entities as parameters

Is it possible if we want to pass entity objects as parameters directly to the background when a get request is made?Let's have a look.

  1. public class TB_CHARGING  
  2.     {  
  3.         /// <summary>  
  4.         /// Primary Key Id  
  5.         /// </summary>  
  6.         public string ID { getset; }  
  7.   
  8.         /// <summary>  
  9.         /// Charging device name  
  10.         /// </summary>  
  11.         public string NAME { getset; }  
  12.   
  13.         /// <summary>  
  14.         /// Charging device description  
  15.         /// </summary>  
  16.         public string DES { getset; }  
  17.   
  18.         /// <summary>  
  19.         /// Creation time  
  20.         /// </summary>  
  21.         public DateTime CREATETIME { getset; }  
  22.     }  
  1. [HttpGet]  
  2. public string GetByModel(TB_CHARGING oData)  
  3. {  
  4.      return "ChargingData" + oData.ID;  
  5. }  
  1. $.ajax({  
  2.         type: "get",  
  3.         url: "http://localhost:27221/api/Charging/GetByModel",  
  4.         contentType: "application/json",  
  5.         data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },  
  6.         success: function (data, status) {  
  7.             if (status == "success") {  
  8.                 $("#div_test").html(data);  
  9.             }  
  10.         }  
  11.     });  

test Result: When a get request is made, we pass the json object directly as an entity to the background, which is not received.Why is that?Let's look at the corresponding http request


  1. <img src="http://images2015.cnblogs.com/blog/459756/201603/459756-20160331104121410-719598113.png" alt="" />  

Originally, when a get request was made, the default was to put all the parameters in the url and pass them directly as string s, which would naturally not be received in the background.

Reason Analysis: Do you remember the interview question asking the difference between get and post requests?One difference is that the data requested by the get is appended to the URL (that is, the data is placed in the HTTP protocol header), while the post request is placed in the package of the HTTP protocol package.

As suggested by the gardeners, you can get the object directly by adding [FromUri] to the parameter when making a Get request.Or paste code:

  1. var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };  
  2.     $.ajax({  
  3.         type: "get",  
  4.         url: "http://localhost:27221/api/Charging/GetAllChargingData",  
  5.         data: postdata,  
  6.         success: function (data, status) { }  
  7.     });  
  1. [HttpGet]  
  2.         public string GetAllChargingData([FromUri]TB_CHARGING obj)  
  3.         {  
  4.             return "ChargingData" + obj.ID;  
  5.         }  

Result:

If you don't want to use [FromUri] as a "bizarre" way of writing that adds attributes to parameters, you can also use serialization followed by back-end deserialization.

  1. $.ajax({  
  2.         type: "get",  
  3.         url: "http://localhost:27221/api/Charging/GetByModel",  
  4.         contentType: "application/json",  
  5.         data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },  
  6.         success: function (data, status) {  
  7.             if (status == "success") {  
  8.                 $("#div_test").html(data);  
  9.             }  
  10.         }  
  11.     });  
  1. [HttpGet]  
  2.         public string GetByModel(string strQuery)  
  3.         {  
  4.             TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);  
  5.             return "ChargingData" + oData.ID;  
  6.         }  

This gives us the object we serialized in the background, and then deserializes it.

In the url we can see that it automatically adds a code to the object:

3. Array as parameter

Arrays are not recommended for general get requests because we know that get requests pass parameters with a limited size, a maximum of 1024 bytes, and passing them as parameters may result in loss of parameter overruns when there is more content in the array.

4.'Strange'get requests

Why would you say get requests are "weird"?Let's first look at the comparison of the two writing methods below.

(1) WebApi method names start with get

  1. $.ajax({  
  2.         type: "get",  
  3.         url: "http://localhost:27221/api/Charging/GetByModel",  
  4.         contentType: "application/json",  
  5.         data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },  
  6.         success: function (data, status) {  
  7.             if (status == "success") {  
  8.                 $("#div_test").html(data);  
  9.             }  
  10.         }  
  11.     });  

  1. [HttpGet]  
  2.         public string GetByModel(string strQuery)  
  3.         {  
  4.             TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);  
  5.             return "ChargingData" + oData.ID;  
  6.         }  

This is the standard notation, plus [HttpGet] in the background, and the parameters are normally obtained:

For comparison, I'll remove [HttpGet] and call it again

  1. //[HttpGet]  
  2.       public string GetByModel(string strQuery)  
  3.       {  
  4.           TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);  
  5.           return "ChargingData" + oData.ID;  
  6.       }  

It looks like there's nothing wrong with it!Someone wonders if all get requests can omit the label [HttpGet].Let's try it.

(2) WebApi method names do not start with get

It's perfectly normal that we change the method name from GetByModel to FindByModel. Many queries don't want to start with Get, and they start with Query.Does this matter?It's okay. Let's tell the truth.


  1. $.ajax({  
  2.         type: "get",  
  3.         url: "http://localhost:27221/api/Charging/FindByModel",  
  4.         contentType: "application/json",  
  5.         data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },  
  6.         success: function (data, status) {  
  7.             if (status == "success") {  
  8.                 $("#div_test").html(data);  
  9.             }  
  10.         }  
  11.     });  

  1. [HttpGet]  
  2.         public string FindByModel(string strQuery)  
  3.         {  
  4.             TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);  
  5.             return "ChargingData" + oData.ID;  
  6.         }  


It looks like it's possible. There's nothing wrong with it.Based on the above deduction, it is also possible to remove [HttpGet]. Okay, let's comment out [HttpGet] and run it for a try.


The result is no breakpoints, some people don't believe, and we look at http requests in our browser:


Heh, that's strange. I changed the method name. As for that?Really!

The blogger's understanding is that the method name starts with Get, and WebApi automatically defaults that this request is a get request. If you start with a different name without labeling the method's request, the server finds this method at this time, but because the request is not sure, it returns you 405 directly - the method is not allowed.

Finally, the conclusion is that all WebApi methods are best served with a request ([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]) and don't be lazy, as this will prevent similar errors and help maintain the method so that others can see what the request is.

That's why many people in the garden ask why a method name can't be called without [HttpGet]!


2. post Request

In the RESETful style of WebApi, the additions and deletions of API services correspond to the post/delete/put/get requests of http, respectively.Let's talk about how the post request parameter is passed.

1. Basic type parameters

The parameters of the basic type of post request and the get request are slightly different. We know that the parameters of the get request are passed through a url, while the post request is passed through the body of the http request, and the WebApi post request also needs to take the parameters from the body of the http request.

(1) Wrong writing

  1. $.ajax({  
  2.         type: "post",  
  3.         url: "http://localhost:27221/api/Charging/SaveData",  
  4.         data: { NAME: "Jim" },  
  5.         success: function (data, status) {  
  6.             if (status == "success") {  
  7.                 $("#div_test").html(data);  
  8.             }  
  9.         }  
  10.     });  

  1. [HttpPost]  
  2.         public bool SaveData(string NAME)  
  3.         {  
  4.             return true;  
  5.         }  

This is a very correct way of writing, but the reality is:


(2) Correct usage

  1. $.ajax({  
  2.        type: "post",  
  3.        url: "http://localhost:27221/api/Charging/SaveData",  
  4.        data: { """Jim" },  
  5.        success: function (data, status) {}  
  6.    });  

  1. [HttpPost]  
  2. public bool SaveData([FromBody]string NAME)  
  3. {  
  4.     return true;  
  5. }  

This is a way of writing that many other people have a headache, but there is no way to get our results:


Our usual mechanism for taking parameters through a URL is a key-value pair, where a key equals a value, unlike our usual mechanism for taking parameters through a url, FromBody here has a mechanism of = value, no concept of key, and if you write a key (such as {NAME:"Jim"} for your ajax parameter), the NAME you get behind the scenes is null.Don't believe you can try it.

So what if we need to pass more than one base type?Based on the above inference, is it possible to write this ([FromBody]string NAME, [FromBody]string DES)?Just try it.

(1) Wrong Writing

  1. $.ajax({  
  2.         type: "post",  
  3.         url: "http://localhost:27221/api/Charging/SaveData",  
  4.         data: { """Jim","":"Remarks" },  
  5.         success: function (data, status) {}  
  6.     });  

  1. [HttpPost]  
  2.         public bool SaveData([FromBody]string NAME, [FromBody] string DES)  
  3.         {  
  4.             return true;  
  5.         }  

Get results


This means we can't get values from multiple [FromBody], and this method fails.

(2) Correct usage

Since that doesn't work, how do we transfer multiple underlying types of data?Many solutions are to create a new class to contain the passed parameters, which the blogger feels is not flexible enough because if we create a new class every post request that passes multiple parameters in front and back, how many of these parameter classes will our system have in time?Maintaining it is quite a hassle!So bloggers think using dynamic is a good choice.Let's try it.

  1. $.ajax({  
  2.         type: "post",  
  3.         url: "http://localhost:27221/api/Charging/SaveData",  
  4.         contentType: 'application/json',  
  5.         data: JSON.stringify({ NAME: "Jim",DES:"Remarks" }),  
  6.         success: function (data, status) {}  
  7.     });  

  1. [HttpPost]  
  2.         public object SaveData(dynamic obj)  
  3.         {  
  4.             var strName = Convert.ToString(obj.NAME);  
  5.             return strName;  
  6.         }  

There is no sense of freshness in passing ajax parameters without using the {""value"} notation of"pointless". ~ It is important to note that the parameter type Json, contentType:'application/json', needs to be added to ajax requests here.

(3) Recommended usage

By requesting the passing of the underlying type parameter from post above, we understand the convenience of dynamic to avoid the cumbersome addition of {":""value"} to [FromBody].The blogger recommends that all base types be passed using dynamic, which facilitates the transfer of one or more parameters of the base type, as shown above.If the gardeners have better ways, welcome to discuss.


3. put Request

put requests in WebApi are typically used for object updates.It is essentially the same as a post request.[FromBody] is also supported, as is dynamic.

1. Basic type parameters

  1. $.ajax({  
  2.         type: "put",  
  3.         url: "http://localhost:27221/api/Charging/Update",  
  4.         contentType: 'application/json',  
  5.         data: JSON.stringify({ ID: "1" }),  
  6.         success: function (data, status) {}  
  7.     });  

  1. [HttpPut]  
  2.         public bool Update(dynamic obj )  
  3.         {  
  4.             return true;  
  5.         }  


2. Entities as parameters

Same as post request.

3. Array as parameter

Same as post request.

IV. delete Request

As the name implies, the delete request must be for the delete operation.The parameter delivery mechanism and post are basically the same.Here is a simple example, other cases referring to post requests.

  1. var arr = [  
  2.         { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },  
  3.         { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" },  
  4.         { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" }  
  5.     ];  
  6.     $.ajax({  
  7.         type: "delete",  
  8.         url: "http://localhost:27221/api/Charging/OptDelete",  
  9.         contentType: 'application/json',  
  10.         data: JSON.stringify(arr),  
  11.         success: function (data, status) {}  
  12.     });  


 

  1. [HttpDelete]  
  2.         public bool OptDelete(List<TB_CHARGING> lstChargin)  
  3.         {  
  4.             return true;  
  5.         }  

V. Summary

This is a more detailed summary of the various parameter passes for various requests for WebApi.Every situation has been tested by the blogger's actual code, and the content is not difficult, but if it takes a little time to get familiar with something like this, here's a summary, hoping to help some new WebApi friends.If this article can help you, you might as well recommend that your recommendation be the motivation for bloggers to continue summarizing!

Topics: JSON