Asp.netCore Summary of restful webapi

Keywords: C# JSON xml IIS Fragment

Last article recorded The concept of WebApi and simple cognitive WebApi , let's explore its applicable scenarios and how to use it today.

Let's briefly talk about the characteristics of WebApi, WCF and WebService, which are widely used:

I. WebService is a lightweight and independent communication technology that can receive requests from other systems on the Internet or Intranet. It has the following characteristics:

1. Based on SOAP Protocol, the data format is XML;

2. The biggest advantage of web Service is cross platform interoperability;

3. Devices supporting Http protocol Xml technology can own and access Web services, but can only be deployed on IIS;

4. Some applications that only need to communicate with other programs on the local machine are not suitable for using web services, for the reason that they are not technically impossible to implement, but that they consume too much and have no benefits.

2. WCF is a unified and efficient development platform that can be used to build safe and reliable service-oriented applications. Its features include:

1. Based on SOAP Protocol, the data format is XML;

2. It can support various protocols, such as TCP, HTTP, HTTPS, Json, etc;

3. Compared with the previous web services, WCF can be deployed not only in IIS but also in applications or Windows services;

4. As long as the standard web service is supported, it can communicate across processes, machines and even platforms.

3. Features of WebApi:

1. The endpoint needs to be specified by URI information. Each URI represents one resource;

2. Different meanings can be expressed through different http actions. The client uses GET, POST, PUT and DELETE to operate the server-side resources: GET is used to obtain resources, POST is used to create new resources (or update resources), PUT is used to update resources, and DELETE is used to DELETE resources;

3. Realize the resource by request. The resource is mostly expressed in XML or HTML (or other forms). The reply to the request can express different meanings through Http Status Code. The client can negotiate with the server through Accept header, such as whether the server wants to return JSON format or XML format or other extended formats;

4. Support cross platform and CORS cross domain calls to WebApi, such as through front-end js or directly in the background. Support self host or IIS during deployment. ;

5. The interaction between the client and the server is stateless. Each request from the client to the server must contain the information necessary to understand the request.

After talking about their characteristics, how to make the best of them? (reference link: https://blog.csdn.net/u013043518/java/article/details/51793294)

1. When you want to create a service that supports message, message queue and duplex communication, you should choose WCF

2. When you want to create a service that can use faster transmission channels, such as TCP, NamedPipes or even UDP (in WCF4.5), HTTP can also be supported when other transmission channels are not available.

3. When you want to create a resource-oriented service based on HTTP and you can use all the features of HTTP (such as URIs, request/response header, cache, version control, multiple content formats), you should choose WebAPI

4. When you want to use your services for browsers, mobile phones, iPhone s and tablets, you should choose Web API

When talking about the features of WebApi, I mentioned that it can be called through the front end or in the background. Let's see how to call it:

Example 1: call Api through HttpClient class. At the same time as Web API publishing,. NET provides two assemblies: System.Net.Http and System.Net.Http.Formatting. The core class in these two assemblies is HttpClient (here we only discuss how to tune WebApi, the idea is to polish a general tool class, and the rest of you can play it freely):

 1 public class CallAPI
 2 {
 3 private static string uri = "http://localhost:5000/";
 4 private HttpClient client = new HttpClient();
 5 
 6 /// <summary>
 7 /// Simple query
 8 /// </summary>
 9 /// <param name="resource">Target resources</param>
10 public void GetData(string resource)
11 {
12   client.BaseAddress = new Uri(uri);
13 
14   // by JSON Format add a Accept Newshead
15   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
16   HttpResponseMessage responseMessage = client.GetAsync(resource).Result;//Get query results
17   if (responseMessage.IsSuccessStatusCode)
18   {
19     var ds = responseMessage.Content.ReadAsStringAsync().Result;
20     string content = JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);//Convert to the format you want xml,json Wait a moment, define the general conversion class, which will not be introduced here. Please create your own
21   }
22 }
23 
24 /// <summary>
25 /// Query with reference
26 /// </summary>
27 /// <param name="resource">Target resources</param>
28 /// <param name="id">ID</param>
29 public void GetDataWithParam(string resource)
30 {
31   client.BaseAddress = new Uri(uri);
32 
33   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
34   HttpResponseMessage responseMessage = client.GetAsync(resource).Result;
35   if (responseMessage.IsSuccessStatusCode)
36   {
37     var ds = responseMessage.Content.ReadAsStringAsync().Result;
38     string content = JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
39   }
40 
41 }
42 
43 
44 /// <summary>
45 /// put Request to update resources
46 /// </summary>
47 /// <param name="resource"></param>
48 /// <returns></returns>
49 public bool PutData(string resource)
50 {
51   bool bol = false;
52   //Create and webapi Corresponding class
53   var content = new FormUrlEncodedContent(new Dictionary<string, string>()
54   {
55     {"ID","382accff-57b2-4d6e-ae84-a61e00a3e3b5"},
56     {"Name","Name" },
57     {"QZH","111"}
58   });
59   HttpResponseMessage response = client.GetAsync(resource).Result;
60   response = client.PostAsync(resource, content).Result;
61   if (response.IsSuccessStatusCode)
62   {
63     bol = true;
64     var result = response.Content.ReadAsStringAsync().Result;
65   }
66   return bol;
67 }
68 
69 }

Example 2: Based on mvc+dotnet core WebApi, call through the front-end ajax, and directly paste several pieces of code of different call types (because Put request is similar to Post request, there is no need to paste code for example):

Segment 1: base type as parameter

 1  front end ajax code:
 2 $.ajax({
 3 type: "get",
 4 url: "http://localhost:27221/api/Charging/GetAllChargingData",
 5 data: { id: 1, name: "Jim", bir: "1988-09-11"},
 6 success: function (data, status) {
 7 if (status == "success") {
 8 $("#div_test").html(data);
 9 }
10 }
11 });
12 Controller Layer code:
13 [HttpGet]
14 public string GetAllChargingData(interestingid,string name, DateTime bir)
15 {return "ChargingData" + id;}

Segment 2: entity type as parameter

 1 front end ajax code: 
 2  $.ajax({
 3 type: "get",
 4 url: "http://localhost:27221/api/Charging/GetByModel",
 5 contentType: "application/json",
 6 data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },
 7 success: function (data, status) {
 8 if (status == "success") {
 9 $("#div_test").html(data);
10 }
11 }
12 });
13 Controller Layer code 1 (serialization first, and then deserialization in the background):
14 [HttpGet]
15 public string GetByModel(string strQuery)
16 {
17 TB_CHARGING oData=Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery));
18 return "Charging" + oData.ID;
19 }
20 Controller Layer code two (add in the parameter[FromUri]): 
21 [HttpGet]
22 [HttpGet]
23 public string GetAllChargingData([FromUri]TB_CHARGING obj)
24 {
25 return "ChargingData" + obj.ID;
26 }

Segment 3: single entity as a parameter: (the default of post request is to send the key/value form of data in the form to the service, and our server only needs the object with the corresponding key/value attribute value to receive it. If application/json is used, it means that the front-end data will be passed to the back-end with serialized json. If the back-end wants to turn it into an entity object, it also needs the process of deserialization.)

 1. Method 1: (using the default parameter type of post request, the front end directly passes the json type object)
 2 front end ajax Code:
 3 $.ajax({
 4 type: "post",
 5 url: "http://localhost:27221/api/Charging/SaveData",
 6 data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
 7 success: function (data, status) {}
 8 });
 9 method 2: (the contentType is specified as application/json, and the object to be passed needs to be serialized)
10 front end ajax Code:
11 var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
12 $.ajax({
13 type: "post",
14 url: "http://localhost:27221/api/Charging/SaveData",
15 contentType: 'application/json',
16 data: JSON.stringify(postdata),
17 success: function (data, status) {}
18 });
19 Controller layer code:
20 [HttpPost]
21 public bool SaveData(TB_CHARGING oData)
22 {
23 return true;
24 }

Fragment 4: solid and base types are passed as parameters together

 1 front end ajax code:
 2 var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
 3 $.ajax({
 4 type: "post",
 5 url: "http://localhost:27221/api/Charging/SaveData",
 6 contentType: 'application/json',
 7 data: JSON.stringify({ NAME:"Lilei", Charging:postdata }),
 8 success: function (data, status) {}
 9 });
10 Controller Layer code:
11 [HttpPost]
12 public object SaveData(dynamic obj)
13 {
14 var strName = Convert.ToString(obj.NAME);
15 var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(Convert.ToString(obj.Charging));
16 return strName;
17 }

Fragment 5: base type array passed as parameter

 1 front end ajax code:
 2     var arr = ["1", "2", "3", "4"];
 3     $.ajax({
 4         type: "post",
 5         url: "http://localhost:27221/api/Charging/SaveData",
 6         contentType: 'application/json',
 7         data: JSON.stringify(arr),
 8         success: function (data, status) { }
 9     });
10 Controller Layer code:
11         [HttpPost]
12         public bool SaveData(string[] ids)
13         {
14             return true;
15         }

Segment 6: simply post a Delete request

 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     });
13 Controller Layer:
14         [HttpDelete]
15         public bool OptDelete(List<TB_CHARGING> lstChargin)
16         {
17             return true;
18         }

Summary: record personal learning Asp.netCore For the process of restful WebApi, please correct the mistakes. In addition: refer to the official website for suggestions on combing the WebApi return value of the Controller layer( https://docs.microsoft.com/zh-cn/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1)

Posted by plex303 on Wed, 17 Jun 2020 18:57:02 -0700