I'm trying to send a http post request in JSON format which should look like this:
{
"id":"72832",
"name":"John"
}
I have attempted to do it like below but if I am correct this is not sending a request in json format.
var values = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://myurl",content);
// code to do something with response
}
How could I modify the code to send the request in json format?
2 Answers 2
try this
using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);
var data = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
//or you can use an anonymous type
//var data = new
//{
// id = 72832,
// name = "John"
//};
var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(api, contentData);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}
If the request comes back with JSON data in the form
{ "return":"8.00", "name":"John" }
you have to create result model
public class ResultModel
{
public string Name { get; set; }
public double Return { get; set; }
}
and code
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultModel>(stringData);
double value = result.Return;
string name = Result.Name;
}
-
Thank you for your response! If the request comes back with Json data in the form ```` { "return":"8.00", "name":"John" } ```` How can I access the value associated to return (in this case "8.00") and store it as a string?Gazdini9991– Gazdini999108/10/2021 08:44:56Commented Aug 10, 2021 at 8:44
-
The code is not quite working as expected - when I am debugging the code var json data looks as follows: "{\"id\":\"72832\",\"name\":\"John\"}" and then contentData doesn't seem to be taking the right form, its value is {System.Net.Http.StringContent} and inside it is Headers, Static members and Non-Public members - I can't seem to find my jsondata anywhere inside the contentDataGazdini9991– Gazdini999108/10/2021 17:24:02Commented Aug 10, 2021 at 17:24
-
@SJ9991 What is the problem?You should not care what is content looks like, Did you check the values inside of the API ? this code was used many many times by many peopele and nobody didn't have any problem.Serge– Serge08/10/2021 17:40:52Commented Aug 10, 2021 at 17:40
-
The code is failing on the var response = ...PostAsync(..) stage, the jsonData looks to be in the correct form when I am debugging the code which is why I thought it may be the contentData. When I catch the error as Exception ex, inside the ExceptionState it says "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" and the HResult is -2146233040Gazdini9991– Gazdini999108/10/2021 22:31:35Commented Aug 10, 2021 at 22:31
-
What is your url when you call PostAsync? It can be wrong url or an API errro. Could you post your API too?Serge– Serge08/10/2021 23:12:17Commented Aug 10, 2021 at 23:12
I would start off by using RestSharp.
dotnet add package RestSharp
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
Just pass in your dictionary as the body object - I would recommend creating a DTOS class to send through though.
Then you can get certain aspects of the RestResponse object that is returned like:
var returnContent = response.Content;
var statusCode = response.StatusCode;