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

C# Send data with method POST to API

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

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

如何正确发送到APIhttps://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"
}

感谢任何线索取得成功

您可以使用 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);