Noel
Noel

Reputation: 5369

http client - exception behaviour

I have the following code, where sometimes the handler I am posting to times out (I do not want to extend the default timeout value) before I get a response. When this happens an AggregateException is throw where there is one InnerExceptions:

[0] {"A task was canceled."} System.Exception {System.Threading.Tasks.TaskCanceledException}

  var _httpClient = new HttpClient();
    var _content = new StringContent("thecontent");
    var responseMessagePost = _httpClient2.PostAsync("http://localhost:50643/handler1.ashx", _content).Result;

Is this the correct behaviour?

I was expecting the variable responseMessagePost to have a Status Code of RequestTimeout = 408. For example when I do the following an exception is not thrown and I get a Status Code of NotFound = 404. Why is the behaviour different?

var httpClient = new HttpClient();
var _content = new StringContent("thecontent");
var _responseMessagePost = httpClient.PostAsync("http://localhost:50643/handlerdoesnotexist.ashx", _content).Result;

Upvotes: 0

Views: 1579

Answers (2)

Ron
Ron

Reputation: 988

I was getting this same error and tracked it down to my HttpClient was timing out. The default timeout is 100 seconds. I added the following to the create of the HttpClient.

HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(10);

Upvotes: 0

Darrel Miller
Darrel Miller

Reputation: 142064

The timeout exception you are getting is due to the HTTP client giving up waiting for the server to produce a response. A 408 is a response from a server when the server gives up waiting for the client to complete it's request.

To my knowledge there is no status code for what you are looking for. If the server was able to return a status code then the client would not have needed to time out!

Upvotes: 2

Related Questions