Timeout a Web Api request?

后端 未结 4 636
轻奢々
轻奢々 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 03:48

    Make your life easier, in your base controller add the following method:

        protected async Task RunTask(Task action, int timeout) {
            var timeoutTask = Task.Delay(timeout);
            var firstTaskFinished = await Task.WhenAny(timeoutTask, action);
    
            if (firstTaskFinished == timeoutTask) {
                throw new Exception("Timeout");
            }
    
            return action.Result;
        }
    

    Now every controller that inherits from your base controller can access the method RunTask. Now in your API call the RunTask method just like that:

        [HttpPost]
        public async Task MyAPI(RequestModel request) {
            try {
                return await RunTask(Action(), Timeout);
            } catch (Exception e) {
                return null;
            }
        }
    
        private async Task Action() {
            return new ResponseModel();
        }
    

提交回复
热议问题