简体   繁体   中英

C# Send data with method POST to API

Dont know what i doing wrong, need to fill database with datas from my VSTO Outlook Addin.

jObjectbody.Add( new { mail_from = FromEmailAddress }); mail_from is name of column in database, FromEmailAddress is value from my Outlook Addin

How to send to API https://my.address.com/insertData correctly ?

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);

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

If i try this in Postman (POST->Body->raw->JSON) data are strored in database, except dont use value just data.

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

thanks for any clue achieve success

You can use restRequest.AddJsonBody(jObjectbody); instead of AddParameter (which I believe adds a query string).

See the RestSharp AddJsonBody docs. They also mention to not use some sort of JObject as it wont work, so you will probably need to update your type as well.

The below might work for you:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM