httclient sendasync issue in .net core

文章讨论了在.NETCoreconsole应用中,使用HttpClient进行HTTP请求时遇到的IOException和SocketException问题。原因是套接字耗尽,建议采用IHttpClientFactory来管理HttpClient实例,以避免端口资源的过度消耗。官方文档推荐的方式可以防止此类问题并提高应用程序的稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

The above code is working in the .net console application but not working in the .net core console application. In .net core console application getting following error.

IOException: 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,

SocketException: The I/O operation has been aborted because of either a thread exit or an application request.

answers1

The reason is because of socket exhaustion.
The resolution is to use IHttpClientFactory to obtain the HttpClient object to make the calls.

翻译:原因是因为套接字耗尽。 解决方案是使用 IHttpClientFactory 获取 HttpClient 对象以进行调用。

answers2

The error appears to indicate your main() which called the httpcliebt code without waiting for the async operation to complete and the program exited before the call completed.

翻译:该错误似乎表明您的 main() 调用了 httpcliebt 代码而不等待异步操作完成并且程序在调用完成之前退出。

answers3

These error can be due to port exhaustion due to not using HttpClient as recommended in the official docs.

翻译:这些错误可能是由于没有按照官方文档中的建议使用 HttpClient 而导致端口耗尽。

相关错误修复链接:

https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Make HTTP requests using IHttpClientFactory in ASP.NET Core | Microsoft Learn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值