[英]Cancel Long operation from Angular to .NET Core
I try to send a cancellation request (on c# AspNetCore based on Abp Boilerplate) from Angular client (use Observable -> unsubscribe...) to cancel long Task Operation but API not fire.我尝试从 Angular 客户端(使用 Observable -> unsubscribe...)发送取消请求(在基于 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
}
on angular side在有角的一侧
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);
I test that if I use TaskSource with CancelAfter all code behind work well but from web (client side) I can't fire the cancellation operation我测试,如果我使用 TaskSource 和 CancelAfter 后面的所有代码运行良好,但从网络(客户端)我无法触发取消操作
You can add a CancellationToken as parameter of you controller action, you don't need to create a CancellationTokenSource in your controller.您可以添加 CancellationToken 作为控制器操作的参数,无需在控制器中创建 CancellationTokenSource。 This token will be cancelled when the HTTP Request is cancelled by the unsubscribe in angular.
当 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
}
I found a solution all depends in wich way Angular close / cancel connection.我找到了一个解决方案,完全取决于 Angular 关闭/取消连接的方式。
I use this solution angular-how-to-cancel-http-calls-on-router-change angular-how-to-cancel-http-calls-on-router-change我使用这个解决方案angular-how-to-cancel-http-calls-on-router-change angular-how-to-cancel-http-calls-on-router-change
I put it on root.module.ts so now when user change route all connection receive cancellation and it close the flow if is implemented.我把它放在 root.module.ts 上,所以现在当用户更改路由时,所有连接都会收到取消,如果实现则关闭流程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.