ResponseCache
在某种程度上是 OutputCache
的替代品;但是,我想进行服务器端缓存以及每个参数输入。
IMemoryCache
或IDistributedCache
来执行此操作。我对参数不同的控制器上的缓存特别感兴趣,以前在 ASP.NET 4 中使用 OutputCache
和 VaryByParam
完成,如下所示:
[OutputCache(CacheProfile = "Medium", VaryByParam = "id", Location = OutputCacheLocation.Server)]
public ActionResult Index(long id)
{
///...
}
我将如何在 ASP.NET Core 中复制它?
如果要通过控制器中所有请求中的所有请求查询参数来更改缓存:
[ResponseCache(Duration = 20, VaryByQueryKeys = new[] { "*" })]
public class ActiveSectionController : ControllerBase
{
//...
}
首先确保您使用的是 ASP.NET Core 1.1 或更高版本。
然后在您的控制器方法上使用与此类似的代码:
[ResponseCache(Duration = 300, VaryByQueryKeys = new string[] { "date_ref" } )]
public IActionResult Quality(DateTime date_ref)
来源:https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware
Asp.Net Core 7 添加了 Output Caching 中间件。这正是您想要的,即服务器缓存。不要将其与您所指的旧 .Net Framework OutputCacheAttribute 混淆。
OutputCache 和 ResponseCache 的主要区别:
您可以将它们用于同一个端点。
在asp.net core中使用它
[ResponseCache(CacheProfileName = "TelegraphCache", VaryByQueryKeys = new[] { "id" })]
对于寻找答案的人...毕竟有 IMemoryCache 但不像以前那么漂亮
ActionFilterAttribute
但具有更多灵活性。services.AddMemoryCache();
服务添加到 ConfigureServices
文件中的 Startup.cs
。public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
3-任意(为了防止拼写错误)声明一个包含一堆键名称的静态类:
public static class CacheKeys
{
public static string SomeKey { get { return "someKey"; } }
public static string AnotherKey { get { return "anotherKey"; } }
... list could be goes on based on your needs ...
我更喜欢声明一个
enum
:public enum CacheKeys { someKey, anotherKey, ...}
_cache.TryGetValue(CacheKeys.SomeKey, out someValue)
TryGetValue
如果失败:
_cache.Set(CacheKeys.SomeKey,
newCachableValue,
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(60)));
结束。
我遇到了同样的问题,以下都没有产生预期的唯一参数值缓存。始终返回初始结果:
VaryByQueryKeys = new[] { "*" }
VaryByQueryKeys = new[] { "searchparam" }
给予
public async Task<IActionResult> Search([FromQuery] string searchparam)
解决方案是在其前面加上
$
,即
VaryByQueryKeys = new[] { "$searchparam" }
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache(); // add this
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseOutputCache(); // add this
app.MapGet("/products/{id}", async (string id) =>
{
return Results.Ok("someresult");
}).CacheOutput(c => c.VaryByValue((context) =>
new KeyValuePair<string, string>(
"id",
context.Request.RouteValues["id"].ToString())));
app.Run();