取消从 Angular 到 .NET Core 的长操作

and*_*tia 1 c# asp.net-core angular abp

我尝试从 Angular 客户端(使用 Observable -> 取消订阅...)发送取消请求(在基于 Abp Boilerplate 的 c# AspNetCore 上)来取消长任务操作,但 API 不触发。

    [HttpPost]
        public async Task<GetDataOutputDto> GetDataLongOperation(CustomInputDto input)
        {
            try
            {
                var tokenSource = new CancellationTokenSource(); // _httpContextAccessor.HttpContext.RequestAborted;
                tokenSource.CancelAfter(2500);

                var token = _httpContextAccessor.HttpContext.RequestAborted; //tokenSource.Token;

                var settings = new JsonSerializerSettings
                {
                    Error = (sender, args) => {
                        args.ErrorContext.Handled = true;
                    },
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };


                //... remove for brev
        }
Run Code Online (Sandbox Code Playgroud)

在有角的一侧

                this.subscription = this.loadData(undefined).subscribe(res=>{
                    console.log('data loaded!');
                    this.localData = res.data;
                    //this._rawData = this.localData;
                    this.loadItems();
                    
                });

                setTimeout(() => {
                    console.log('TEST stop long') 
                    this.subscription.unsubscribe();
                }, 2500);
Run Code Online (Sandbox Code Playgroud)

我测试如果我将 TaskSource 与 CancelAfter 一起使用,所有代码都运行良好,但从网络(客户端)我无法触发取消操作

J.L*_*cos 5

您可以添加 CancellationToken 作为控制器操作的参数,无需在控制器中创建 CancellationTokenSource。当 HTTP 请求被 Angular 中的取消订阅取消时,该令牌将被取消。

        [HttpPost]
        public async Task<GetDataOutputDto> GetDataLongOperation(CustomInputDto input, CancellationToken token)
        {
            try
            {
                var settings = new JsonSerializerSettings
                {
                    Error = (sender, args) => {
                        args.ErrorContext.Handled = true;
                    },
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };
        }
        catch(TaskCanceledException e)
        {
            //The observable was unsubscribed in angular
        }
Run Code Online (Sandbox Code Playgroud)