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>();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章