Jydai
Jydai

Reputation: 21

Error while sending POST request to API (Cannot send a body with this verb type)

I always get this error when I try to request the API. Some details about the api : the method is POST and the parameters are correct, too (When I try it on postman, no issue)

Here is my code:

JavaScriptSerializer js = new JavaScriptSerializer();
using (WebClient client = new WebClient())
{
    foreach (var ad in documents)
    {

        var doc = js.Serialize(ad);
        var json = "{\"Message\":\"" + doc + "\"}";

        var response =
            client.UploadValues("apiUrl", new NameValueCollection()
            {
                {"json", json}
            });
    }
}

I read that UploadValues is POST by default. This code is called in a simple console app. Any idea why I get this error ?

Upvotes: 0

Views: 500

Answers (1)

Jydai
Jydai

Reputation: 21

Here is a working piece of code :

var doc = JsonConvert.SerializeObject(message);    
var stringContent = new StringContent(
        message,
        UnicodeEncoding.UTF8,
        "application/json");

HttpClient client = new HttpClient();                

client.PostAsync("apiUrl", stringContent);

Upvotes: 2

Related Questions