Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel .Net Core Web API request using Angular?

I have the following two applications

  • Angular 6/7 App
  • .Net Core Web API

I am making GET request to API using Angular's HttpClient as shown below

this.subscription = this.httpClient.get('api/Controller/LongRunningProcess')
                                   .subscribe((response) => 
                                   {
                                      // Handling response
                                   });

API controller's LongRunningProcess method has the following code

    [HttpGet]
    [Route("LongRunningProcess")]
    public async Task<IActionResult> LongRunningProcess(CancellationToken cancellationToken)
    {
        try
        {
            // Dummy long operation
            await Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    // Option 1 (Not working)
                    if (cancellationToken.IsCancellationRequested)
                        break;

                    // Option 2 (Not working)
                    cancellationToken.ThrowIfCancellationRequested();

                    Thread.Sleep(6000);
                }

            }, cancellationToken);
        }
        catch (OperationCanceledException e)
        {
            Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {e.Message}");
        }

        return Ok();
    }

Now I want to cancel this long-running process so I am unsubscribing from client side as shown below

// On cancel button's click
this.subscription.unsubscribe();

Above code will cancel the request and I can see it is canceled in the Network tab of the browser as shown below

enter image description here

But it is not going to make IsCancellationRequested to true in the method LongRunningProcess of the API, so the operation will keep going.

[Note]: Both Option 1 and Option 2 in API method are not working even if I make a call using postman.

Question: Is there any way to cancel that LongRunningProcess method's operation?

like image 850
Advait Baxi Avatar asked Sep 01 '19 13:09

Advait Baxi


People also ask

How do I cancel a CancellationToken request?

When given a CancellationToken , you can create a new instance of the token source, assign it's token to the provided token, and cancel it. All other parties that can read this token will see that it's cancellation has been requested.

What is cancellation token in .NET core?

You can use a CancellationToken to stop a long running operation when the user cancels a request in the web browser. In other words, using a CancellationToken can help you stop long running requests from using resources when the user has stopped or refreshed the web page.

Should I use CancellationToken?

Whether you're doing async work or not, accepting a CancellationToken as a parameter to your method is a great pattern for allowing your caller to express lost interest in the result. Supporting cancelable operations comes with a little bit of extra responsibility on your part.

How do cancellation tokens work?

This model is based on a lightweight object called a cancellation token. The object that invokes one or more cancelable operations, for example by creating new threads or tasks, passes the token to each operation. Individual operations can in turn pass copies of the token to other operations.


1 Answers

When angular cancel request, you can get cancellation token from http context

   CancellationToken cancellationToken = HttpContext.RequestAborted;
    if (cancellationToken.IsCancellationRequested)
    {
        // The client has aborted the request
    }
like image 147
divyang4481 Avatar answered Sep 19 '22 22:09

divyang4481