1

I am trying to cancel a long-running action on the server side when the client cancels or aborts the request. I am using ASP.Net Core 6.0 and the fetch API with Signal. HttpContext.RequestAborted.IsCancellationRequested is always false.

while (true)
{
   CancellationToken cancellationToken = HttpContext.RequestAborted;

   if (cancellationToken.IsCancellationRequested)
   {
      tokenSource2.Cancel();
   }
}
1
  • can this blog help you? it also related to cancel token
    – Tiny Wang
    Commented Aug 3, 2023 at 9:49

1 Answer 1

0

You can add a CancellationToken to your action and pass it down to your long-running task:

[HttpGet("slow")]
public async Task<string> Get(CancellationToken cancellationToken)
{
    // Your slow action
    var result = await CalculateResultAsync(10000, cancellationToken);

    return result;
}

And in your long-running task:

public async Task<string> CalculateResultAsync(int input, CancellationToken cancellationToken)
{
    for(var i = 0; i < input; i++)
    {
        cancellationToken.ThrowIfCancellationRequested();

        await Task.Delay(1000);
    }

    return "Finished!";
}

7
  • Could you tell me, How can I call using fetch(url, options) from the client side? Commented Aug 2, 2023 at 15:22
  • @NishilAthikkal You don't need to do anything special in the client side, when you close the tab for example the browser will send a cancelled message to the server which in turn will trigger CancellationToken in your C# code
    – ctyar
    Commented Aug 2, 2023 at 15:28
  • I am getting IsCancellationRequested always as false. But on the client-side request is already cancelled, I can see it Network tab. I tried HttpContext.RequestAborted.IsCancellationRequested but got false after the client cancels the request. (using fetch() to call the API) Commented Aug 2, 2023 at 16:40
  • @NishilAthikkal I've edited my answer and added how you would use the CancellationToken
    – ctyar
    Commented Aug 2, 2023 at 17:10
  • I used this, but in my scenario, even though the client terminated the request, the server-side 'IsCancellationRequested' is false. hence it is not throwing the exception. Commented Aug 3, 2023 at 2:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.