【发布时间】:2019-08-15 17:14:44
【问题描述】:
我创建了一个全新的 ASP.NET Core Web API 项目。这是 Startup.cs 中的ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var cache = serviceProvider.GetService<IMemoryCache>();
cache.Set("key1", "value1");
//_cahce.Count is 1
}
如您所见,我将一个项目添加到 IMemoryCache。这是我的控制器:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IMemoryCache _cache;
public ValuesController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet("{key}")]
public ActionResult<string> Get(string key)
{
//_cahce.Count is 0
if(!_cache.TryGetValue(key, out var value))
{
return NotFound($"The value with the {key} is not found");
}
return value + "";
}
}
当我请求https://localhost:5001/api/values/key1 时,缓存是空的,我收到一个未找到的响应。
【问题讨论】:
-
你能分享你的 MemoryCache 类吗? ..为什么不使用 Redis 。 .so重启时不会丢失数据?
-
你确定
key的值和"key1"一样吗? -
@federicoscamuzzi - 我怀疑他们使用的是this,这很难让它成为“他们的”。
-
我怀疑您现在可能有 2 个服务提供者,因为您正在构建自己的以添加到缓存中,但这可能不是 ASP.NET 使用的那个。我没试过,但我猜他们会返回不同的实例。
标签: c# asp.net-core .net-core