Timeout a Web Api request?

后端 未结 4 655
轻奢々
轻奢々 2020-12-30 03:37

Like MVC WebApi runs on the asynchronous ASP.NET pipeline, meaning execution timeout is unsupported.

In MVC I use the [AsyncTimeout] filter, WebApi does

4条回答
  •  渐次进展
    2020-12-30 04:02

    With WebAPI, you would generally handle timeouts on the client side, rather than the server side. This is because, and I quote:

    The way to cancel HTTP requests is to cancel them on the HttpClient directly. The reason being that multiple requests can reuse TCP connections within a single HttpClient and so you can't safely cancel a single request without possibly affecting other requests as well.

    You can control the timeout for requests -- I think it's on the HttpClientHandler if I recall correctly.

    If you really need to implement a timeout on the API side itself, I would recommend creating a thread to do your work in, and then cancelling it after a certain period. You could for example put it in a Task, create your 'timeout' task using Task.Wait and use Task.WaitAny for the first one to come back. This can simulate a timeout.

    Similarly, if you are performing a specific operation, check to see if it already supports timeouts. Quite often, I will perform an HttpWebRequest from my WebAPI, and specify its Timeout property.

提交回复
热议问题