override default asp.net core cancelationtoken or change default timeout for requests.

babak fakhriloo 41 Reputation points
2021-06-29T09:19:11.033+00:00

In my asp.net core 5.0 app, I call an async method that might take some time to be processed.

await someObject.LongRunningProcess(cancelationToken);

However, I want that method to be timeout after 5 seconds. I know that instead of "cancelationToken" passed by asp.net core action, I can use "CancellationTokenSource" :

var s_cts = new CancellationTokenSource();
s_cts.CancelAfter(TimeSpan.FromSeconds(5);

await someObject.LongRunningProcess(s_cts );

Is it possible to use "CancellationTokenSource" as a default "Cancelation Token" policy for all asp.net core requests ? I mean override the one which is passed as a parameter of the action ?

Or is it possible to change the default timeout for all request in asp.net core 5.0 ?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,561 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Rijwan Ansari 746 Reputation points MVP
    2022-03-04T05:21:23.313+00:00
    0 comments No comments

  2. Bruce (SqlWork.com) 65,476 Reputation points
    2022-03-04T17:49:17.547+00:00

    note: while you can set the cancellation token in middleware, all your actions still need to pass it to any async tasks they call. also be sure the tasks honor the cancellation token.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.