阿里巴巴网站装修怎么做全屏大图,高大上的广告公司名字,中文域名网站建设,wordpress首页新文章加newWinform程序调用WebApi的方式有很多#xff0c;本文学习并记录采用HttpClient调用基于GET、POST请求的WebApi的基本方式。WebApi使用之前编写的检索环境检测数据的接口#xff0c;如下图所示。
调用基于GET请求的无参数WebApi 创建HttpClient实例后调用GetStringAsync函数获… Winform程序调用WebApi的方式有很多本文学习并记录采用HttpClient调用基于GET、POST请求的WebApi的基本方式。WebApi使用之前编写的检索环境检测数据的接口如下图所示。
调用基于GET请求的无参数WebApi 创建HttpClient实例后调用GetStringAsync函数获取返回json字符串如果返回的是基本数据则按需调用格式转换函数将转换返回字符串格式主要代码如下所示
string url http://localhost:5098/ECData/ECDataCount;
HttpClient client new HttpClient();
int result Convert.ToInt32(client.GetStringAsync(url).Result);如果返回复杂数据格式则需预定义数据类然后调用反序列化函数将返回的json字符串反序列化为指定数据类型的实例对象。需注意的是返回的json字符串中的属性名称的大小写与数据类定义中的属性名称大小写的对应关系。本文测试时使用System.Text.Json反序列化并配置JsonSerializerOptions忽略大小写。主要代码如下所示 string url http://localhost:5098/ECData/ECDatas;HttpClient client new HttpClient();string result client.GetStringAsync(url).Result;JsonSerializerOptions options new JsonSerializerOptions();options.PropertyNameCaseInsensitive true;List EnvironmentRecord lstRecords JsonSerializer.DeserializeListEnvironmentRecord(result, options);调用基于GET请求的带参数WebApi 调用基于GET请求的带参数WebApi其请求参数基本都是附在url最后传递到服务端此时调用webapi的方式和上一小节一致如下所示
string url http://localhost:5098/ECData/List?page1;
HttpClient client new HttpClient();
string result client.GetStringAsync(url).Result;
JsonSerializerOptions options new JsonSerializerOptions();
options.PropertyNameCaseInsensitive true;
ListFuncResult lstRecords JsonSerializer.DeserializeListFuncResult(result, options);调用基于POST请求的带参数WebApi通过url传递参数 调用基于Post请求的带参数WebApi如果请求参数通过url传递则调用webapi的方式和上一小节一致仅调用函数变为PostAsync。主要代码如下所示
string url http://localhost:5098/ECData/DataTableListByPost?page1limit10;
HttpClient client new HttpClient();
string result client.PostAsync(url,null).Result.Content.ReadAsStringAsync().Result;
JsonSerializerOptions options new JsonSerializerOptions();
options.PropertyNameCaseInsensitive true;
DataTableFuncResult lstRecords JsonSerializer.DeserializeDataTableFuncResult(result, options);调用基于POST请求的带参数WebApi通过请求体传递参数 通过请求体传递参数的话需先将参数序列化为字符串然后创建StringContent对象保存字符串最终调用PostAsync发送post请求。主要代码如下所示
string url http://localhost:5098/ECData/DataTableListByPostPlus;
HttpClient client new HttpClient();QueryCondition condition new QueryCondition();
condition.page 1;
condition.limit 10;var content new StringContent(JsonSerializer.SerializeQueryCondition(condition), Encoding.UTF8);
content.Headers.Remove(Content-Type);
content.Headers.Add(Content-Type, application/json);string result client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
JsonSerializerOptions options new JsonSerializerOptions();
options.PropertyNameCaseInsensitive true;
DataTableFuncResult lstRecords JsonSerializer.DeserializeDataTableFuncResult(result, options);参考文献 [1]https://blog.csdn.net/yanzean/article/details/126860942 [2]https://blog.csdn.net/lg_2_lr/article/details [3]https://www.cnblogs.com/rengke2002/p/7921003.html