asp.net core:如何设置单个actionroute的requesttimeout?

问题描述 投票:1回答:1

在asp.net core中,如何为单个动作route设置requesttout?requesttimeout 为一个动作?

我知道我可以设置webconfig: enter image description here

但这是全局的,而且我只想在一个动作上有一个较长的超时。

asp.net asp.net-core asp.net-core-webapi
1个回答
0
投票

你可以自己在controller方法中实现超时。

public async Task<IActionResult> DoNotHang()
{
    var timeout = TimeSpan.FromMinutes(1);
    var operation = LongOperationAsync(); // no "await" here!

    if (await Task.WhenAny(operation, Task.Delay(timeout)) == operation)
    {
        var result = await operation; // obtain result (if needed)
        return Ok(result == null ? "Null" : "Not null");
    }
    else
    {
        return Ok("Timed out (but still working, not cancelled)");
    }
}

异步等待任务<T>超时完成。 了解更多关于超时等待的细节,包括当一个任务完成时取消 "其他 "任务。

© www.soinside.com 2019 - 2024. All rights reserved.