【问题标题】:C# Send data with method POST to APIC# 使用 POST 方法向 API 发送数据
【发布时间】:2020-10-12 13:18:02
【问题描述】:

不知道我做错了什么,需要用我的 VSTO Outlook 插件中的数据填充数据库。

jObjectbody.Add( new { mail_from = FromEmailAddress }); mail_from 是数据库中列的名称,FromEmailAddress 是我的 Outlook 插件中的值

如何正确发送到 API https://my.address.com/insertData

RestClient restClient = new RestClient("https://my.address.com/");

JObject jObjectbody = new JObject();
jObjectbody.Add( new { mail_from = FromEmailAddress });

RestRequest restRequest = new RestRequest("insertData", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("text/html", jObjectbody, ParameterType.RequestBody);

IRestResponse restResponse = restClient.Execute(restRequest);

错误:Could not determine JSON object type for type <>f__AnonymousType0`1[System.String].

如果我在 Postman (POST->Body->raw->JSON) 中尝试此操作,数据会存储在数据库中,但不要仅使用 value 数据。

{
"mail_from":"email@email.com"
}

感谢任何线索取得成功

【问题讨论】:

    标签: c# json api vsto


    【解决方案1】:

    您可以使用restRequest.AddJsonBody(jObjectbody); 代替AddParameter(我相信它会添加一个查询字符串)。

    请参阅RestSharp AddJsonBody 文档。他们还提到不要使用某种JObject,因为它不起作用,因此您可能还需要更新您的类型。

    以下内容可能对您有用:

    RestClient restClient = new RestClient("https://my.address.com/");
    
    var body = new { mail_from = "email@me.com" };
    
    RestRequest restRequest = new RestRequest("insertData", Method.POST);
    restRequest.AddJsonBody(body);
    
    IRestResponse restResponse = restClient.Execute(restRequest);
    
    // extra points for calling async overload instead
    //var asyncResponse = await restClient.ExecuteTaskAsync(restRequest);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2012-09-10
      • 1970-01-01
      相关资源
      最近更新 更多