3

In asp.net core, how can you set the requesttimeout for a single action?

I know I can set the webconfig: enter image description here

but this is global, and I want a longer timeout on only one action.

Sean
  • 13,396
  • 11
  • 70
  • 110
Neallin
  • 93
  • 1
  • 1
  • 5

1 Answers1

0

You may implement timeout yourself in controller method:

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

See Asynchronously wait for Task<T> to complete with timeout for more details on await-ing with timeout, including cancellation of "other" task when one completes.

Dmitry
  • 14,925
  • 4
  • 57
  • 71