ASP.NET MVC缓存

huangapple go评论69阅读模式
英文:

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&lt;IActionResult&gt; Image([FromQuery, Required] long id)
{
     // code removed for readability

     if(fileNotFound)
     {
          // Send no-cache header
          // returns &quot;placeholder&quot; image
     }
    
     // If file found -&gt; 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&lt;IActionResult&gt; Image([FromQuery, Required] long id)
{
     // 为了提高可读性而删除的代码

     if(fileNotFound)
     {
          // 发送无缓存标头
          Response.Headers.CacheControl = &quot;no-cache&quot;;
          
          // 返回&quot;占位符&quot;图像
     }
    
     // 如果找到文件 -&gt; 设置缓存
     Response.Headers.CacheControl = &quot;max-age=2630000&quot;; // 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&lt;IActionResult&gt; Image([FromQuery, Required] long id)
{
     // code removed for readability

     if(fileNotFound)
     {
          // Send no-cache header
          Response.Headers.CacheControl = &quot;no-cache&quot;;
          
          // returns &quot;placeholder&quot; image
     }
    
     // If file found -&gt; set cache
     Response.Headers.CacheControl = &quot;max-age=2630000&quot;; // 1 month
}

huangapple
  • 本文由 发表于 2023年3月7日 03:28:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定