.NET核心Web API中是否可以取消呼叫?

时间:2019-10-08 21:13:04

标签: .net .net-core

我们有一个.NET Framework前端,它调用.NET Core Web API来检索要显示给用户的项目。如果用户呼叫了成千上万的项目,然后决定取消请求,则它可能会吞噬资源,继续获取我们知道用户不再希望检索的项目。一旦调用了该服务,.NET中是否可以取消该调用?

1 个答案:

答案 0 :(得分:4)

查看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;
    }
}

您可以改为这样做

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;
    }
}

您没有提到前端的外观,但是您需要某种方式来从客户端请求中发出取消信号。一个例子。

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

//If the user navigates away from this page
xhr.abort()

这里有很好的例子

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