英文:
ASP.NET MVC Caching
问题
我有一个AssetsController
,其中有一个端点:
[HttpGet]
public async Task<IActionResult> Image([FromQuery, Required] long id)
{
// 为了可读性已删除的代码
if(fileNotFound)
{
// 发送无缓存头
// 返回“占位符”图像
}
// 如果找到文件 -> 设置缓存
}
我想要设置缓存,以便浏览器不必每次访问时都加载资源。
每个图像都有一个分配的ID,这个ID保持不变,这意味着由特定ID返回的数据不会更改。此端点用于返回UI元素,如图标。
启用仅对此端点启用缓存的最简单/最佳方法是什么?
英文:
In my AssetsController
I have an endpoint:
[HttpGet]
public async Task<IActionResult> Image([FromQuery, Required] long id)
{
// code removed for readability
if(fileNotFound)
{
// Send no-cache header
// returns "placeholder" image
}
// If file found -> set cache
}
I want to set up caching, so that the browser doesn't have to load the resource every time I visit.
Each image gets an assigned id which stays the same, meaning that data returned by a specific id doesn't change. This endpoint is used to return ui elements, like icons.
What would be the easiest/best way to enable caching only for this endpoint?
答案1
得分: 0
在玩了一会儿后,我找到了一个方法来做到这一点。
我这样做,看起来运行得很顺利:
[HttpGet]
public async Task<IActionResult> Image([FromQuery, Required] long id)
{
// 为了提高可读性而删除的代码
if(fileNotFound)
{
// 发送无缓存标头
Response.Headers.CacheControl = "no-cache";
// 返回"占位符"图像
}
// 如果找到文件 -> 设置缓存
Response.Headers.CacheControl = "max-age=2630000"; // 1 个月
}
英文:
After playing around a bit I have found a way to do this.
I do it like this and it seems to be working just fine:
[HttpGet]
public async Task<IActionResult> Image([FromQuery, Required] long id)
{
// code removed for readability
if(fileNotFound)
{
// Send no-cache header
Response.Headers.CacheControl = "no-cache";
// returns "placeholder" image
}
// If file found -> set cache
Response.Headers.CacheControl = "max-age=2630000"; // 1 month
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论