Like MVC WebApi runs on the asynchronous ASP.NET pipeline, meaning execution timeout is unsupported.
In MVC I use the [AsyncTimeout]
filter, WebApi does
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();
}