.NET Core Web API 中有没有办法取消呼叫?

Rya*_*yan 3 .net .net-core

我们有一个 .NET Framework 前端,它调用 .NET Core Web API 来检索要向用户显示的项目。如果用户调用数以万计的项目,然后决定取消请求,则可能会耗尽继续获取用户不再想要检索的项目的资源。.NET 中是否有一种方法,一旦调用已到达服务,就可以取消调用?

Dud*_*001 6

查看 CancellationTokens

在示例控制器中

public class SlowRequestController : Controller
{
    private readonly ILogger _logger;

    public SlowRequestController(ILogger<SlowRequestController> logger)
    {
        _logger = logger;
    }

    [HttpGet("/slowtest")]
    public async Task<string> Get()
    {
        _logger.LogInformation("Starting to do slow work");

        // slow async action, e.g. call external api
        await Task.Delay(10_000);

        var message = "Finished slow delay of 10 seconds.";

        _logger.LogInformation(message);

        return message;
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以这样做

public class SlowRequestController : Controller
{
    private readonly ILogger _logger;

    public SlowRequestController(ILogger<SlowRequestController> logger)
    {
        _logger = logger;
    }

    [HttpGet("/slowtest")]
    public async Task<string> Get(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Starting to do slow work");

        for(var i=0; i<10; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            // slow non-cancellable work
            Thread.Sleep(1000);
        }
        var message = "Finished slow delay of 10 seconds.";

        _logger.LogInformation(message);

        return message;
    }
}
Run Code Online (Sandbox Code Playgroud)

您没有提到前端是什么样子,但您需要某种方法来发出客户端请求取消的信号。一个例子可能是。

var xhr = $.get("/api/slowtest", function(data){
  //show the data
});

//If the user navigates away from this page
xhr.abort()
Run Code Online (Sandbox Code Playgroud)

这里有很好的例子

https://andrewlock.net/using-cancellationtokens-in-asp-net-core-mvc-controllers/

和这里

https://www.davepaquette.com/archive/2015/07/19/cancelling-long-running-queries-in-asp-net-mvc-and-web-api.aspx

  • 如果您要从网络上的文章中批量复制代码,您至少可以做的就是向作者表示感谢... https://andrewlock.net/using-cancellationtokens-in-asp-net-core- mvc-控制器/ (4认同)