Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert string to system.Net.HttpContent [duplicate]

Here I'm trying to get data from the services:

public async Task<IHttpActionResult> ValidateSesion()
{
    var values = new Dictionary<string, string>{
        { "productId", "1" },
        { "productKey", "Abc6666" },
        { "userName", "OPPO" },
    };
    var json = JsonConvert.SerializeObject(values, Formatting.Indented);
    // var content = new FormUrlEncodedContent(json);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.PostAsync("http://172.116.12.172:8014/iadmin/validate", json);
    var responseString = await response.Content.ReadAsStringAsync();
    return Ok(responseString);
}

If I make any PostMan call, like below, the data i get looks like this:

{
    "productId": "1",
    "productKey": "Abc6666" 
}
like image 201
mahesh sad Avatar asked Feb 05 '19 07:02

mahesh sad


1 Answers

You can't post a raw string, you have to wrap it in a StringContent: new StringContent(json);

This should do the trick:

public async Task<IHttpActionResult> ValidateSesion()
{
    var values = new Dictionary<string, string>{
      { "productId", "1" },
      { "productKey", "Abc6666" },
      { "userName", "OPPO" },
    };

    var json = JsonConvert.SerializeObject(values, Formatting.Indented);

    var stringContent = new StringContent(json);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsync("http://172.116.12.172:8014/iadmin/validate", stringContent);

    var responseString = await response.Content.ReadAsStringAsync();

    return Ok(responseString);
}
like image 145
Tobias Tengler Avatar answered Nov 01 '22 17:11

Tobias Tengler