ASP.NET Core 7.0、.NET 7.0中的CacheOutput()中间件默认持续时间为60秒。如果需要更改持续时间,可以在中间件的构造函数中指定缓存持续时间(以秒为单位)。
以下代码示例演示如何使用CacheOutput()中间件以及如何指定缓存持续时间:
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
// CacheOutput()中间件,默认持续时间为60秒
[HttpGet("sample1")]
[CacheOutput]
public IActionResult Sample1()
{
// 处理代码
return Ok();
}
// CacheOutput()中间件,持续时间为120秒
[HttpGet("sample2")]
[CacheOutput(ClientTimeSpan = 120)]
public IActionResult Sample2()
{
// 处理代码
return Ok();
}
}
在上面的示例中,Sample1()
方法使用CacheOutput()中间件,持续时间为默认值60秒。而Sample2()
方法也使用CacheOutput()中间件,但是持续时间为120秒,这是通过指定ClientTimeSpan
属性来实现的。
需要注意的是,CacheOutput()中间件会将响应缓存到客户端(浏览器),因此缓存持续时间的有效性取决于客户端缓存的有效期。如果客户端在缓存期限内再次发出相同的请求,则不会到服务器请求数据,而是直接使用先前缓存的响应数据。