gpt4 book ai didi

c# - HttpClient 超时似乎不起作用

转载 作者:行者123 更新时间:2023-11-30 15:16:52 32 4
gpt4 key购买 nike

我有一个如下所示的 Web API Controller :

[Route("api/[controller]")]
public class SlowController : Controller
{
[HttpPost]
public ActionResult Post([FromBody]SlowRequest request)
{
var response = new SlowResponse();
response.Id = request.Id;
response.StartDate = DateTime.Now;
Thread.Sleep(new TimeSpan(0, 3, 0));
response.EndDate = DateTime.Now;

return Ok(response);
}
}

请注意如何睡 3 分钟。这是为了模拟post Action 需要很长时间才能返回。

我有一个调用此 Web API 的客户端控制台应用程序:

static void Main(string[] args)
{
try
{
var request = new SlowRequest();
request.Id = Guid.NewGuid();

var json = JsonConvert.SerializeObject(request);

var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 5, 0);
httpClient.BaseAddress = new Uri("http://localhost:54316/");
var result = httpClient.PostAsync("api/slow", new StringContent(json, Encoding.UTF8, "application/json")).Result.EnsureSuccessStatusCode();
var apiResponse = result.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<SlowResponse>(apiResponse);

Console.WriteLine("Start Time = " + response.StartDate);
Console.WriteLine("End Time = " + response.EndDate);

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

不幸的是,客户端在 2 分钟后抛出异常:

Response status code does not indicate success: 502 (Bad Gateway).

似乎如果 API 需要超过 2 分钟才能返回此信息,则会发生异常。不到 2 分钟,它工作得很好。尽管事实上我已经为客户端设置了 5 分钟的超时时间。如何防止需要很长时间的 Web API 调用出现这样的错误?

最佳答案

不是客户端的问题,是服务端的问题。你让它休眠了 3 分钟,这超过了默认的请求超时时间。您可以在 web.config 中更改它:

<aspNetCore requestTimeout="00:05:00" ... />

请注意,该值只能指定为整分钟,否则默认为 2 分钟。查看Core configuration reference .

Kersel 也有一个 2 分钟的超时,您需要在 Program.cs 中更改它:

.UseKestrel(o => o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5));

参见 Keep​Alive​Timeout Property .

注意:我假设您的项目是核心项目。如果不是这种情况,您必须更改 web.config 中的 executionTimeout 属性。默认为 110 秒:

<system.web>
<httpRuntime executionTimeout="300" />
</system.web>

参见 ExecutionTimeout Property .

关于c# - HttpClient 超时似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410388/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com