C#使用POST方法将数据发送到API

时间:2020-10-12 13:18:02

标签: c# json api vsto

不知道我在做什么错,需要使用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].

如果我在邮递员(POST-> Body-> raw-> JSON)中尝试此操作,则数据将存储在数据库中,除非不要仅使用value数据。

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

感谢任何线索取得成功

1 个答案:

答案 0 :(得分: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);