您是否曾经访问过一个网站,它需要很长时间加载,最终你敲击 f5 重新加载页面。
即使用户刷新了浏览器取消了原始请求,而对于服务器来说,api也不会知道它正在计算的值将在结束时被丢弃,刷新五次,服务器将触发 5 个请求。
为了解决这个问题,asp.net core 为 web 服务器提供了一种机制,就是cancellationtoken.
用户取消请求时,你可以使用httpcontext.requestaborted访问,您也可以使用依赖注入将其自动注入到您的操作中。
长时间运行的任务请求
现在我们假设您有一个 api 操作,在向用户发送响应之前可能需要一些时间才能完成。
在处理该操作时,用户可以直接取消请求,或刷新页面(这会有效地取消原始请求,并启动新请求)。
[httpget(name = "get")]
public async task<string> getasync()
{
try
{
_logger.loginformation("request in");
await task.delay(5 * 1000);
_logger.loginformation("request end");
}
catch (exception ex)
{
_logger.loginformation("request ex");
}
return "ok";
}如果用户在请求中途刷新浏览器,那么浏览器永远不会收到第一个请求的响应,但在server端可以看到,操作方法执行完成两次。

这是否是正确将取决于您的应用程序。
如果请求修改某些业务的状态,那么您可能不希望在方法中途停止执行。如果请求没有副作用,那么您可能希望尽快停止(可能很昂贵)操作。
用户取消请求时,你可以使用httpcontext.requestaborted访问,您也可以使用依赖注入将其自动注入到您的操作中。
cancellationtokens取消不必要的请求
以下代码显示了如何通过将cancellationtokensource 注入到操作方法中,并通过其取消不必要的操作。
[httpget(name = "get")]
public async task<string> getasync(cancellationtoken cancellationtoken)
{
try
{
_logger.loginformation("request in");
await task.delay(5 * 1000,cancellationtoken);
_logger.loginformation("request end");
}
catch (exception ex)
{
_logger.loginformation("request ex");
}
return "ok";
}通过这个改变,我们可以再次测试我们的场景。
我们发出一个初始请求,然后我们重新加载页面。正如您从下面的日志中看到的,第一个请求不会继续执行。

用户刷新浏览器取消请求后不久,原始请求就会中止,并taskcancelledexception通过 api 过滤器管道传播回来,并备份中间件管道。
根据您的场景,您可能能够依靠此类框架方法来检查 的状态cancellationtoken,或者您可能需要自己监视取消请求。
过滤器捕获异常
您可以通过以上try catch 捕获,或者通过一个过滤器统一监视此异常。
public class operationcancelledexceptionfilter : exceptionfilterattribute
{
private readonly ilogger _logger;
public operationcancelledexceptionfilter(iloggerfactory loggerfactory)
{
_logger = loggerfactory.createlogger<operationcancelledexceptionfilter>();
}
public override void onexception(exceptioncontext context)
{
if (context.exception is operationcanceledexception)
{
_logger.loginformation("request was cancelled");
context.exceptionhandled = true;
context.result = new statuscoderesult(400);
}
}
}
builder.services.addcontrollers(options =>
{
options.filters.add<operationcancelledexceptionfilter>();
});
到此这篇关于.net core使用 cancellationtoken 取消api请求的文章就介绍到这了,更多相关.net core取消api请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论