Thursday 15 October 2020

Resolving “System.IO.IOException: The response ended prematurely.” in HttpClient Request

Some times a silly mistake can waste lot of time of a developer. The exception “System.IO.IOException: The response ended prematurely.” while making an http client request to call an API from another web app has wasted considerable amount of my time diagnosing the issue. Therefore, thought worth sharing the experience.

The error reported was below when an API request via http client was made from one of the web applications. Strangely the other web application handled the same request with no problems and returned the expected data.

Sending HTTP request GET http://localhost:5001/api/v1/businessTypes/1/ServiceCategories

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]

An unhandled exception has occurred while executing the request.

System.Net.Http.HttpRequestException: An error occurred while sending the request.

---> System.IO.IOException: The response ended prematurely.

at System.Net.Http.HttpConnection.FillAsync(Boolean async)

at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean async, Boolean foldedHeadersAllowed)

at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

--- End of inner exception stack trace ---

This caused me to look at each implementation compared closely and I could not see any difference. Exactly same code patterns were implemented so I was pulling my hair for some time with this one, as it seems something somewhere wrong but was 100% certain it is not the code as there was no difference at all. After spending couple of hours searching for this “The response ended prematurely.” in web there was no proper reasoning could be found.

Finally, figured out the cause of the issue, accidentally and it was too silly mistake by a developer carelessly put the API url with HTTPS port while having set the url for api as http. The https port was set as 5001 and the http port was set as 5000 in the development environment of the said API. However the developer has used, http://localhost:5001 which I did not see straight away while trying to figure out what was wrong. It was just one ‘s’ wasted good couple of hours.

With this experience I would like to recommend all developers out there, just don’t type in these types of stuff in your app settings even while at the time of development times. Instead, just copy it from the source (in this case from the launchsettings.json in the API had the two urls) as shown below so should have copied the https url to the calling web app appsettings file which would have saved my time as well as the developers time as well.

No comments:

Popular Posts