目前我有以下操作,它将告诉客户端将响应缓存 1200 秒:
[ResponseCache(Location = ResponseCacheLocation.Client, Duration = 1200)]
[HttpGet("universities")]
public IActionResult GetAllUniversities(string location)
{
if (/*location not found*/)
return BadRequest();
...
return Ok(universities);
}
在响应 header 中,当它返回 Ok (200) 时,我收到以下值:
Cache-Control: private, max-age=1200
正如预期的那样完美。
当我将错误的位置传递给 API 并且 API 返回 BadRequest (400) 时,它也会返回与上面相同的 Cache-Control 值。
我的问题是,这是最佳实践吗?或者它应该返回 no-cache, no-store
而不是 400?如果应该,我如何在 200 时返回 private, max-age=1200
并仅针对此特定操作在 .NET Core 中返回 no-cache, no-store
?
最佳答案
您应该使用ASP.NET Core 中的响应缓存中间件,它仅缓存 200 个状态代码响应,并忽略其他错误响应。
有关如何实现的更多信息,请参阅 - https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware?tabs=aspnetcore2x
关于c# - Bad Request的Cache-Control最佳实践(400),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47088611/