0

The below code is working in the .NET console application but not working in the .NET core console application.

In the .NET Core console application I'm getting the error message

The operation was canceled

and the InnerException is

Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request
var client = new HttpClient();
            
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.nseindia.com/option-chain");
httpRequestMessage.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
httpRequestMessage.Headers.Add("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpRequestMessage.Headers.Add("Accept-Language", "en-us,en;q=0.5");
httpRequestMessage.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
var response = await client.SendAsync(httpRequestMessage);
Ajayakumar GS
  • 19
  • 1
  • 3

1 Answers1

2

Option 1 - Increase Timeout

My first inclination when looking at this problem was to suggest that the default timeout was different for .NET Framework vs. .NET Core/.NET. I looked at the documentation for HttpClient.Timeout (here and here) and the default timeout is the same: 100 seconds.

I was going to suggest increasing the value in this case. Even knowing now the default is the same, I suggest increasing the value anyway. It may be that there are enough other differences in the implementations and/or how you're reaching your destination from two different clients that a change in timeout might make sense.

So try setting Timouout to say TimeSpan.FromMinutes(5) and see where that gets you. Here are some other resources

Option 2 - Use IHttpClientFactory

Your code indicates that you're creating a client and using it all at once in some scope, and suggests that you are not using it for the lifetime of the application. If that's true, you will run into issues such as socket exhaustion.

While that link talks about the original .NET Framework HttpClient that you're not having issues with, I suggest you follow the advice of the link and use IHttpClientFactory to create your client instead. It may be that you "coded to a bug" against the original, and the .NET Core version/way of doing things has exposed this.

Kit
  • 20,354
  • 4
  • 60
  • 103