ASP.NET Core中处理中止的请求

原文: ASP.NET Core中处理中止的请求

当用户向应用程序发出请求时,服务器将解析该请求,生成响应,然后将结果发送给客户端。用户可能会在服务器处理请求的时候中止请求。就比如说用户跳转到另一个页面中获取说关闭页面。在这种情况下,我们希望停止所有正在进行的工作,以浪费不必要的资源。例如我们可能要取消SQL请求、http调用请求、CPU密集型操作等。

ASP.NET Core提供了HTTPContext.RequestAborted检测客户端何时断开连接的属性,我们可以通过IsCancellationRequested以了解客户端是否中止连接。

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public async Task<WeatherForecast> Get()
    {
        CancellationToken cancellationToken = HttpContext.RequestAborted;
        if (cancellationToken.IsCancellationRequested)
        {
            //TODO aborted request
        }

        return await GetWeatherForecasts(cancellationToken);
    }

    private async Task<WeatherForecast> GetWeatherForecasts(CancellationToken cancellationToken)
    {
        await Task.Delay(1000, cancellationToken); 
        return  Array.Empty<WeatherForecast>();
    }
}

当然我们可以通过如下代码片段以参数形式传递

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public async Task<WeatherForecast> Get(CancellationToken cancellationToken)
    {
        return await GetWeatherForecasts(cancellationToken);
    }

    private async Task<WeatherForecast> GetWeatherForecasts(CancellationToken cancellationToken)
    {
        await Task.Delay(1000, cancellationToken); 
        return  Array.Empty<WeatherForecast>();
    }
}

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12969279.html