zoukankan      html  css  js  c++  java
  • 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>();
        }
    }
    
  • 相关阅读:
    Go-15-flag.String 获取系统参数
    Go-14-解决 go get golang.org/x/text 拉取失败问题
    Go-08-函数与指针
    redis 学习(6)-- 集合类型
    redis 学习(5)-- 列表类型
    redis 学习(4)-- 哈希类型
    redis 学习(3)-- String 类型
    redis 学习(二)-- 通用命令
    redis 学习(1)-- redis 安装与启动
    Mysql 索引原理及优化
  • 原文地址:https://www.cnblogs.com/yyfh/p/12968591.html
Copyright © 2011-2022 走看看