0

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;
Noel
  • 5,037
  • 9
  • 46
  • 69

2 Answers2

2

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!

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • So is the expected behaviour for http client to throw an exception when a timeout occurs? – Noel Aug 15 '12 at 12:22
  • @Noel I'm also trying to detect timeouts (and distinguish them from user cancellations using a CancellationToken), but the returned TCE doesn't seem to have the information that allows me to do it. In any event, if your request times out, you won't get an HTTP response. So you will have to take the actual behavior as the expected behavior, I fear. – Evgeniy Berezovsky Oct 01 '12 at 02:15
  • @EugeneBeresovsky TaskCancellationException has a CancellationToken property that you should be able to compare with the one you passed to the method. Will this not work? – Søren Boisen May 22 '15 at 09:32
  • @SørenBoisen Unfortunately, [`TaskCanceledException.CancellationToken == CancellationToken.None`](http://stackoverflow.com/questions/12666922/distinguish-timeout-from-user-cancellation). For reasons I do not understand. Also, I want to handle the exception places where I do not have a reference to the original CancellationToken, so that I don't have to pass state around (or create global static state). – Evgeniy Berezovsky May 24 '15 at 23:19
0

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);

Ron
  • 978
  • 3
  • 13
  • 27