1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

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

Discussão em 'Angular' iniciado por Advait Baxi, Outubro 10, 2024 às 07:22.

  1. Advait Baxi

    Advait Baxi Guest

    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

    [​IMG]

    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?

    Continue reading...

Compartilhe esta Página