POST in Web API returns Invalid Content Type

2

I'm trying to send a POST request to a Web API.

If I do it by Postman, it works:

NowwhenItrytoexecutethroughcode,Igetthefollowingerror:

{"status": false,
    "message": "Content Type Inválido. (Formato aceito: Content Type = \"application/json\" ",
    "total": 0
}

I've tried it this way:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Constants.APIV2);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));

string json = JsonConvert.SerializeObject(billing);

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Constants.Billing);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");

await client.SendAsync(request)
    .ContinueWith(responseTask =>
    {
        var teste = responseTask.Result.Content.ReadAsStringAsync();
    });

And this:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Constants.APIV2);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));

string json = JsonConvert.SerializeObject(billing);

HttpResponseMessage response = await client.PostAsync(Constants.Billing, new StringContent(json, Encoding.UTF8, "application/json"));

if (response.IsSuccessStatusCode)
{
    var result = response.Content.ReadAsStringAsync();
}

And to no avail.

Any idea what I might be doing wrong?

    
asked by anonymous 23.03.2018 / 18:41

1 answer

2

Just a hint, keep in memory the instance of your HttpClient , in your PostAsync you should only enter the relative path. Understand why by reading the following article: YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

In fact, your code seems correct, I usually do it as follows

public class WebApiProxy
{
    private static HttpClient Client;

    static Base()
    {
        // var cookieContainer = new CookieContainer();
        // var httpClientHandler = new HttpClientHandler();
        // httpClientHandler.CookieContainer = cookieContainer;
        // Client = new HttpClient(httpClientHandler);

        Client = new HttpClient();
        client.BaseAddress = new Uri(Constants.BaseUrl);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));
    }

    public async Task<Resposta> SendBilling(Billing billing)
    {
        var json = JsonConvert.SerializeObject(billing);
        var httpRequest = new HttpRequestMessage(HttpMethod.Post, Constants.RelativePath);
        httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
        using (var request = await Client.SendAsync(httpRequest))
        {
            if (request.IsSuccessStatusCode)
            {
                var responseJson = await request.Content.ReadAsStringAsync();
                var responseWrap = JsonConvert.DeserializeObject<Resposta>(responseJson);
                return responseWrap;
            }
        }
        return null;
    }
}

EDIT

Chatting with the AP through Chat, we identified that the problem was poorly done validation performed by the API.

The HttpClient sends together with Content-Type CHARSET , such behavior is included in the protocol specification: W3C

But the API did not behave as expected when it received a Content-Type with CHARSET , thus ignoring the request.

As a contour solution, it was necessary to remove charset from Content-Type .:

var content = new StringContent(json, Encoding.UTF8, "application/json"); 
content.Headers.ContentType.CharSet = string.Empty;
    
23.03.2018 / 18:54