6

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?

Paul Wheeler
20.3k3 gold badges32 silver badges46 bronze badges
asked Aug 9, 2021 at 23:45

2 Answers 2

12

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;
}
TylerH
21.2k82 gold badges81 silver badges119 bronze badges
answered Aug 10, 2021 at 0:44
8
  • 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? Commented 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 contentData Commented 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. Commented 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 -2146233040 Commented 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? Commented Aug 10, 2021 at 23:12
2

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;
answered Aug 10, 2021 at 8:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.