httpclient PostAsJsonAsync (n)消息后错误(端口耗尽?)
本文关键字:PostAsJsonAsync 消息 httpclient 错误 | 更新日期: 2023-09-27 18:05:13
我有一个在Azure中运行的控制台应用程序(webjob),它调用在Azure中运行的API。控制台应用程序从csv文件发布消息。当我从本地(windows 10)机器上运行控制台应用程序(在azure中运行api)时,它按预期工作(没有错误)。当我在Azure中运行控制台应用程序(在Azure中运行api)时,它处理大约980条消息,然后开始报告错误
错误:
- "发送请求时发生错误"
- "无法连接到远程服务器"
我相信,由于某种原因,当控制台应用程序在Azure中运行时,它正在耗尽端口,但我不知道如何解决这个问题。我的文件有50,000行,但如前所述,在问题出现之前只有大约980行。在另一端,api将接收到的消息发送到sql数据库和azure事件中心。一旦PostAsJsonAsync完成,我如何强制应用程序释放端口?如何检查端口是否已释放,或者如何检查端口是否可用?如果你知道我可能得到这些错误的任何其他原因,请帮助。
下面是我的代码:public async Task<string> PostMessageToAPI(string aMsg)
{
HttpResponseMessage response = null;
string strResponse = "";
try
{
using (var client = new HttpClient())
{
client.SetBearerToken("access token here");
client.BaseAddress = new Uri("MyBaseUrl.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (response = await client.PostAsJsonAsync("my/url/goes/here", anEvent.ToLower()))
{
if (response != null)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException(response.ReasonPhrase);
}
else
{
return await response.Content.ReadAsStringAsync();
}
}
}
}
}
catch (HttpRequestException ex)
{
// exception message states: "An error occurred while sending the request"
}
return strResponse;
}
- Visual Studio 2015 update 3
- . net 4.5.1
- Azure控制台应用程序计划:基本1小
- Azure API应用程序计划:基本1小
请不要将HttpClient
包裹在using
中。使用静态实例并共享它
public class MyClass()
{
private HttpClient client = null;
public MyClass(){
client = new HttpClient();
client.SetBearerToken("access token here");
client.BaseAddress = new Uri("MyBaseUrl.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> PostMessageToAPI(string aMsg)
{
HttpResponseMessage response = null;
string strResponse = "";
try
{
using (var response = await client.PostAsync("my/url/goes/here", new StringContent(aMsg, Encoding.UTF8, "application/json")))
{
if (response != null)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException(response.ReasonPhrase);
}
else
{
return await response.Content.ReadAsStringAsync();
}
}
}
}
catch (HttpRequestException ex)
{
// exception message states: "An error occurred while sending the request"
}
return strResponse;
}
}
你甚至可以共享类的相同实例,关键是,每次重新创建和重新打开套接字并不是最佳的,它最终会导致套接字耗尽,这取决于你的调用吞吐量。
源