前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET Core中处理中止的请求

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

作者头像
HueiFeng
发布2020-05-27 10:10:39
7830
发布2020-05-27 10:10:39
举报
文章被收录于专栏:HueiFeng技术专栏

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

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

代码语言:javascript
复制
[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>();
    }
}

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

代码语言:javascript
复制
[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>();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档