一、简介
    最近,在做一个数据传输的服务,我在一个Worker Service里面需要访问 WebAPI 接口,并传输数据,也可以提交数据。由于第一次使用 RestSharp 发送请求,也遇到了很多问题,不过最终把问题都解决了。什么东西都一样,第一次做都会才很多坑。
    今天,我就两个小的知识点,就是通过使用 RestSharp 访问 WebAPI,提交 FromBody 和 FromForm 两种方式的数据,还是有些区别的。我当初也搞了一段时间。
    我先说一下我的编码环境:
        操作系统:Windows 10 Professional
        开发工具:Visual Studio 2022
        客户端程序:Worker Service
        服务端程序:Net Core WebAPI
        框架版本:Net7.0
二、我的代码
    以下我就介绍一下,使用 RestSharp、以FromBody 和 FromForm 两种方式提交数据的实现,废话不多说,直接上代码。如果是重点代码,我会以红色标注。
       WebAPI 端的代码:
    

    [HttpPost]
        public async Task<CommonJsonResult<string>> AddOrUpdateScannerSetting([FromBody]/[FromForm] ScannerSettingInputDto inputDto)
        {
              
        }

 

      其他的代码不用细看,都是我的逻辑代码。
      Worker Service 端的代码:

 1        using (RestClient restClient = new RestClient())
 2             {
 3                 var updateScannerSettingRequest = new RestRequest(new Uri(updateScannerSettingUrl), Method.Post);
 4                 updateScannerSettingRequest.AddHeader("Authorization", "Bearer " + token);//增加的 JWT 认证
 5                 updateScannerSettingRequest.AddHeader("Accept", "application/json");
 6                 updateScannerSettingRequest.RequestFormat = DataFormat.Json;
 7 
 8                 #region [FromBody]接收,这里有两种方式,都是可以的
 9 
10                 1、updateScannerSettingRequest.AddParameter("application/json", JsonConvert.SerializeObject(scannerSettingInputDto), ParameterType.RequestBody);
11                 2、updateScannerSettingRequest.AddBody(scannerSettingInputDto);
12 
13                 #endregion
14 
15                 #region [FromForm]接收,所有字段都需要自己添加
16 
17                 updateScannerSettingRequest.AddParameter("ScannerId", scannerSettingInputDto.ScannerId);
18                 updateScannerSettingRequest.AddParameter("Camera1Id", scannerSettingInputDto.Camera1Id);
19                 updateScannerSettingRequest.AddParameter("Camera2Id", scannerSettingInputDto.Camera2Id);
20                 updateScannerSettingRequest.AddParameter("Camera3Id", scannerSettingInputDto.Camera3Id);
21                 updateScannerSettingRequest.AddParameter("Camera4Id", scannerSettingInputDto.Camera4Id);
22                 updateScannerSettingRequest.AddParameter("Camera1IntegrationTime", scannerSettingInputDto.Camera1IntegrationTime);
23                 updateScannerSettingRequest.AddParameter("Camera2IntegrationTime", scannerSettingInputDto.Camera2IntegrationTime);
24                 updateScannerSettingRequest.AddParameter("Camera3IntegrationTime", scannerSettingInputDto.Camera3IntegrationTime);
25                 updateScannerSettingRequest.AddParameter("Camera4IntegrationTime", scannerSettingInputDto.Camera4IntegrationTime);
26                 updateScannerSettingRequest.AddParameter("Camera1Image", scannerSettingInputDto.Camera1Image);
27                 updateScannerSettingRequest.AddParameter("Camera2Image", scannerSettingInputDto.Camera2Image);
28                 updateScannerSettingRequest.AddParameter("Camera3Image", scannerSettingInputDto.Camera3Image);
29                 updateScannerSettingRequest.AddParameter("Camera4Image", scannerSettingInputDto.Camera4Image);
30                 updateScannerSettingRequest.AddParameter("ScannerCoordinate", scannerSettingInputDto.ScannerCoordinate);
31                 updateScannerSettingRequest.AddParameter("PatrolFile", scannerSettingInputDto.PatrolFile);
32                 updateScannerSettingRequest.AddParameter("WarningPhone", scannerSettingInputDto.WarningPhone);
33                 updateScannerSettingRequest.AddParameter("IsUpdate", scannerSettingInputDto.IsUpdate);
34                 updateScannerSettingRequest.AddParameter("Remarks", scannerSettingInputDto.Remarks);
35 
36                 #endregion
37 
38                 var updateScannerSettingResponse = await restClient.ExecuteAsync(updateScannerSettingRequest);
39                 var updateScannerSettingContent = updateScannerSettingResponse.Content;
40                 if (!string.IsNullOrEmpty(updateScannerSettingContent) && !string.IsNullOrWhiteSpace(updateScannerSettingContent))
41                 {
42                     var commontResultObject = JsonConvert.DeserializeObject<CommonJsonResult<string>>(updateScannerSettingContent);
43                     if (commontResultObject != null && commontResultObject.Success)
44                     {
45                         result = true;
46                     }
47                     else
48                     {
49                         result = false;
50                         _logger.LogError(updateScannerSettingContent);
51                     }
52                 }
53                 else
54                 {
55                     result = true;
56                 }
57             }

    还有一个辅助类型:

 1 /// <summary>
 2     /// 该类型定义了以 JSON 为返回结果的通用数据格式。
 3     /// </summary>
 4     /// <typeparam name="TResult">结果的返回类型。</typeparam>
 5     public sealed class CommonJsonResult<TResult>
 6     {
 7         /// <summary>
 8         /// 获取或者设置操作的结果是成功还是失败,True 表示操作成功,False 表示操作失败。
 9         /// </summary>
10         public bool Success { get; set; }
11 
12         /// <summary>
13         /// 获取或者设置操作的结果编码值。
14         /// </summary>
15         public int StateCode { get; set; }
16 
17         /// <summary>
18         /// 获取或者设置操作的提示信息。
19         /// </summary>
20         public string? Message { get; set; }
21 
22         /// <summary>
23         /// 获取或者设置数据的结果。
24         /// </summary>
25         public TResult? DataResult { get; set; }
26     }

 

三、总结

     好了,记录好了,下次自己有需要就不用急了。不忘初心,继续努力。

posted on 2023-09-21 15:28  可均可可  阅读(1301)  评论(0编辑  收藏  举报