How to set the request timeout for one controller

2020-03-19 04:22发布

I need to increase the request timeout for a specific controller action in my application programmatically in the controller.

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-19 04:52

The best way I have found so far to handle a long running script (if your application simply can't avoid having one) is to firstly create an async handler:

public async Task<IActionResult> About()
    {
            var cts = new CancellationTokenSource();            
            cts.CancelAfter(180000);
            await Task.Delay(150000, cts.Token);
        return View();
    }

In the snippet above I have added a Cancellation token to say that my Async Method should cancel after 180 seconds (even though in this example it will never delay for longer than 150 seconds) I've added the timeout to ensure there is a cap on how long my script can run.

If you run this you will get a HTTP Error 502.3 since there is a timeout set on the httpPlatform of 00:02:00.

To extend this timeout go to the web.config file inside the wwwroot folder and add a requestTimeout="00:05:00" property to the httpPlatform element. For Example:

<httpPlatform requestTimeout="00:05:00" processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600"/>

The long running script should now work.

This does, however, mean that any request will take 5 minutes to timeout so you will have to ensure that you use the CancellationToken trick to limit any Async requests you have in your application. In previous versions of MVC we had the AsyncTimeOut attribute that you could add to a controller, but it appears that this has been cut in MVC6 See GitHub aspnet/mvc Issue #2044

查看更多
登录 后发表回答