HttpClient timeout error calling PostAsJsonAsync

1

I am having a problem getting the response from the HttpClient PostAsJsonAsync method. I am passing a StringContent data to a POST request but it returns a Forbidden (403) status code.

When I tried adding a default request header (commented line of code), the error changed and it returned a timeout issue:

{System.Net.Http.WinHttpException (0x80072EE2): The operation timed out at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Threading.Tasks.RendezvousAwaitable`1.GetResult() at System.Net.Http.WinHttpHandler.d__105.MoveNext()}

var content = new StringContent(JsonConvert.SerializeObject(contentBody), Encoding.UTF8, "application/json");

var client = new HttpClient();
client.BaseAddress = new Uri("https://www.example.com");
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

using (var httpResponse = await client.PostAsJsonAsync("api/details", content))
{
    if (httpResponse.Content != null)
    {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
    }
}

When I tried it in Postman, it returned the JSON data. Why doesn't it work in the code? Is there something that blocks my connection?

c#
httpclient
asked on Stack Overflow Jun 21, 2019 by Reynner Adonay • edited Jun 21, 2019 by Reynner Adonay

1 Answer

2

The BaseAddress property needs to be suffixed with a forward slash:

client.BaseAddress = new Uri("https://www.example.com/");
answered on Stack Overflow Jun 21, 2019 by Dan D

User contributions licensed under CC BY-SA 3.0