Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send JSON data in http post request C#

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?

like image 767
Gazdini9991 Avatar asked Aug 31 '26 02:08

Gazdini9991


1 Answers

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;
}
like image 198
Serge Avatar answered Sep 02 '26 17:09

Serge