如何在.NET Core中实现图片缓存?基于Cache Tag Helper的实现咨询
Hey there! Nice to see you leveraging the Cache Tag Helper—you’re already on the right track. Let’s walk through how to adapt that time-based example to handle image caching effectively in your .NET Core app.
Basic Wrapping for Static/Dynamic Images
The core approach is to wrap your image element (or the code that renders it) inside the <cache> tag. Here’s a straightforward example for images served via a query-string-based endpoint:
<cache enabled="true" vary-by-query="id"> <img src="/images/serve?id=@Model.ImageId" alt="Cached User Avatar" /> </cache>
Why vary-by-query?
If your images are fetched with unique identifiers (like an image ID in the query string), this attribute ensures each distinct image gets its own cache entry—no overwriting the same cache for every image. If your image URLs use route parameters (e.g., /images/serve/{id}), swap it for vary-by-route="id" instead.
Caching Generated Images (Resize, Watermarks, etc.)
If you’re dynamically generating images (resizing, adding watermarks, etc.) via a controller action, wrap the entire image call in the cache tag. For example, if you have an action Images/Resized/{id}/{size}:
<cache enabled="true" vary-by-route="id,size" duration="3600"> <img src="@Url.Action("Resized", "Images", new { id = Model.ImageId, size = "medium" })" alt="Resized Cached Image" /> </cache>
duration: Sets how long the cache entry persists (in seconds)—tweak this based on how often your images are updated (e.g., 86400 for 24 hours).vary-by-route: Ensures every combination ofidandsizegets a unique cached version, so a medium-sized image of ID 1 doesn’t overwrite the small version of the same image.
Pro Tips for Effective Caching
- Cache Invalidation: If you need to update an image before the cache expires, use the
cache-keyattribute to define a unique, predictable key for each image. For example:
You can then invalidate this specific key using<cache enabled="true" cache-key="image_@Model.ImageId_@Model.Size" duration="86400"> <img src="/images/generate?imageId=@Model.ImageId&size=@Model.Size" alt="Custom Cached Image" /> </cache>IDistributedCache(if using distributed caching) when the image is updated. - Distributed Caching: For multi-server setups, switch to a distributed cache (like Redis or SQL Server) instead of the default in-memory cache. The Cache Tag Helper will automatically use your configured provider, ensuring consistency across servers.
- Cache Limits: Large images can bloat your cache quickly. Use the
sizeattribute to cap the maximum size of individual cached entries, or configure eviction policies (like LRU) in your cache provider to manage storage.
内容的提问来源于stack exchange,提问作者Toshi Kishino

