我有以下两个应用
- 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();
上面的代码将取消请求,我可以在浏览器的网络标签中看到它被取消了,如下所示
但它不会在 API 的方法 LongRunningProcess 中使 IsCancellationRequested 为 true,因此操作将继续进行。
[注意]即使我使用 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/