【问题标题】:IMemoryCache get return null after setting a value asp.net core 2.2IMemoryCache 在设置值 asp.net core 2.2 后返回 null
【发布时间】:2019-12-17 17:08:03
【问题描述】:

我正在尝试在我的 ASP.NET CORE 2.2 Web API 应用程序中使用 IMemoryCache 服务。我在启动时的 ConfigureServices 函数中添加了该服务(.AddMemoryCache())。 在开始使用它之前,我决定测试一下,看看我是否可以成功地设置一个值并通过使用该服务来检索它。 不幸的是,每当我设置一个值然后尝试检索它时,API 响应都会返回 204 No Content found。 我做错了什么,请帮忙。 谢谢。

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddMvc();
    }

然后在我的 TestController 中

namespace JwtTut.Controllers
{
    [Route("api")]
    public class TestController : Controller
    {
    private readonly ILogger _logger;
    private readonly ApplicationDbContext _context;
    private readonly UserManager<IdentityUser> userManager;
    private readonly RoleManager<IdentityRole> roleManager;
    private readonly IIdentityService _identityService;
    private IMemoryCache _memoryCache;

    public TestController(ILogger<TestController> logger, ApplicationDbContext context,
        UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager,
        IIdentityService identityService, IMemoryCache memoryCache)
    {
        _logger = logger;
        _context = context;
        this.userManager = userManager;
        this.roleManager = roleManager;
        _identityService = identityService;
        _memoryCache = memoryCache;
    }

    [HttpGet("user-claims")]
    public IActionResult GetUserClaims()
    {
        var randomList = new List<string>();
        for (int i = 0; i < 20; i++)
        {
            randomList.Add($"{i}");
        }

        _memoryCache.Set("randomLIst", randomList);
        var fromCache = _memoryCache.Get<string>("randomList");

        return Ok(fromCache);
    }
}

}

我正在使用 api/user-claims 来测试 IMemoryCache 服务

【问题讨论】:

  • 请分享您的代码
  • 我已经添加了我的代码,请看一下

标签: asp.net-core caching asp.net-core-2.1


【解决方案1】:

看下面两行。您用于设置缓存的键(randomLIst)与您用于获取缓存的键(randomList)不同:

_memoryCache.Set("randomLIst", randomList);
var fromCache = _memoryCache.Get<string>("randomList");

已更正:

_memoryCache.Set("randomList", randomList);
var fromCache = _memoryCache.Get<string>("randomList");

我建议你为缓存键创建一个单独的实用程序类以避免印刷错误。

【讨论】:

  • 傻我!谢谢兄弟!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
相关资源
最近更新 更多