Gazdini9991
Gazdini9991

Reputation: 79

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?

Upvotes: 6

Views: 24850

Answers (2)

Serge
Serge

Reputation: 43959

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

Upvotes: 12

jallmen
jallmen

Reputation: 134

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;

Upvotes: 2

Related Questions