c# - 如何使用 Angular 取消 .Net Core Web API 请求?

标签 c# angular asp.net-core asp.net-core-2.0 asp.net-core-webapi

我有以下两个应用

  • Angular 6/7 应用
  • .Net 核心 Web API

我正在使用 Angular 的 HttpClient 向 API 发出 GET 请求,如下所示

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

API Controller 的LongRunningProcess方法有如下代码

    [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();
    }

现在我想取消这个长时间运行的进程,所以我从客户端取消订阅,如下所示

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

上面的代码将取消请求,我可以在浏览器的网络标签中看到它被取消了,如下所示

enter image description here

但它不会在 API 的方法 LongRunningProcess 中使 IsCancellationRequestedtrue,因此操作将继续进行。

[注意]即使我使用 postman 进行调用,API 方法中的选项 1选项 2 都不起作用。

问题:有什么方法可以取消LongRunningProcess方法的运行吗?

最佳答案

angular cancel请求时,可以从http context获取取消token

   CancellationToken cancellationToken = HttpContext.RequestAborted;
    if (cancellationToken.IsCancellationRequested)
    {
        // The client has aborted the request
    }

关于c# - 如何使用 Angular 取消 .Net Core Web API 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746297/

相关文章:

c# - 'CustomerId' 操作的结果中不存在所需的列 'FromSql'

javascript - 防止在 Asp.Net Core ViewComponents 中加载多个 JavaScript 脚本

c# - 检查列表中的对象是否具有特定字段内容

c# - WP7 - 动画结束得太早,没有效果

angular - 测试依赖于服务的管道

regex - Angular 8 自定义货币掩码

Angular 5 Material 垫选择 : filter based on value selected,

C# 等同于/Gh 标志

c# - 映射器使用多线程?

asp.net-core - 参数化 IdentityServer 中的 LoginUrl?