.NET CORE接口调用接口代码 03

 

1.调用修改接口

 

 

 

代码:

 1 /// <summary>
 2         /// 请求接口 修改学生 https://localhost:5001/WeatherForecast/修改学生用户
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpPost("UpdateStudent")]
 6         public async Task<string> UpdateStudent_Async(Student_Model SM)
 7         {
 8             //string jsonstr = JsonConvert.SerializeObject(CM);//C#将实体类转为JSON字符串
 9 
10             string url = "https://localhost:5001/WeatherForecast/修改学生用户";
11             string responseBody = "";
12             try
13             {
14                 var str = JsonConvert.SerializeObject(SM);
15                 HttpContent content = new StringContent(str);//API传参可放实体模型
16                 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
17 
18                 using (var client = new HttpClient())
19                 {
20                     HttpResponseMessage response = await client.PostAsync(url, content);//改成自己的
21                     response.EnsureSuccessStatusCode();//用来抛异常的
22                     responseBody = await response.Content.ReadAsStringAsync();
23                 }
24 
25             }
26             catch (Exception ex)
27             {
28                 Console.WriteLine(ex.Message);
29             }
30             return responseBody;
31         }

 

 

2.调用删除接口

 1 /// <summary>
 2         /// 请求接口 删除班级 https://localhost:5001/WeatherForecast/删除班级?CId=1009
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpPost("DeleteClass")]
 6         public async Task<string> DeleteClass_Async(int CId)
 7         {
 8             string url = "https://localhost:5001/WeatherForecast/删除班级?CId=" + CId;
 9 
10             string responseBody = "";
11             try
12             {
13                 var str = JsonConvert.SerializeObject("213123");
14                 HttpContent content = new StringContent(str);
15                 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
16 
17                 using (var client = new HttpClient())
18                 {
19                     HttpResponseMessage response = await client.PostAsync(url, content);//改成自己的
20                     response.EnsureSuccessStatusCode();//用来抛异常的
21                     responseBody = await response.Content.ReadAsStringAsync();
22                 }
23 
24             }
25             catch (Exception ex)
26             {
27                 Console.WriteLine(ex.Message);
28             }
29             return responseBody;
30         }

 

posted @ 2022-08-19 17:25  Bruce_Sun  阅读(222)  评论(0)    收藏  举报