You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Redis缓存实现遇System.ArgumentNullException的解决方法

解决ASP.NET Core 6中Redis分布式缓存的System.ArgumentNullException问题

针对你遇到的调用_distributedCache.GetStringAsync(cacheKey)时抛出"参数'configuration'为空"的错误,按以下步骤排查解决:

  • 检查Redis服务的依赖注入配置
    确保在Program.cs中正确注册StackExchange.Redis分布式缓存服务,且配置项已正确读取连接字符串:

    builder.Services.AddStackExchangeRedisCache(options =>
    {
        // 从appsettings.json读取Redis连接字符串
        options.Configuration = builder.Configuration.GetConnectionString("Redis");
        // 可选:设置缓存实例名称,避免多应用共用Redis时键冲突
        options.InstanceName = "StudentsApi:";
    });
    

    同时确认appsettings.json中的连接字符串配置无误:

    "ConnectionStrings": {
        "Redis": "localhost:6379,password=yourRedisPassword"
    }
    

    若options.Configuration未赋值,会导致注入的IDistributedCache实例内部配置为空,直接触发ArgumentNullException。

  • 验证仓储类的构造函数注入
    确保StudentsRepository的构造函数正确注入IDistributedCache接口,而非手动实例化具体实现类:

    public class StudentsRepository : IStudentsRepository
    {
        private readonly IDistributedCache _distributedCache;
        private readonly IDbConnection _dbConnection;
    
        public StudentsRepository(IDistributedCache distributedCache, IDbConnection dbConnection)
        {
            // 提前校验注入实例,避免后续空引用
            _distributedCache = distributedCache ?? throw new ArgumentNullException(nameof(distributedCache));
            _dbConnection = dbConnection ?? throw new ArgumentNullException(nameof(dbConnection));
        }
    
        // 仓储方法实现...
    }
    

    禁止手动new RedisCache(),这种方式无法传入正确配置,必然导致内部configuration为空。

  • 确认连接字符串读取有效性
    可在Program.cs中临时添加控制台输出,验证连接字符串是否被正确读取:

    var redisConnStr = builder.Configuration.GetConnectionString("Redis");
    Console.WriteLine($"Redis连接字符串: {redisConnStr}");
    

    若输出为null,说明appsettings.json的ConnectionStrings节点配置有误,或者配置文件未被正确加载。

  • 检查NuGet包版本兼容性
    确保StackExchange.Redis和Microsoft.Extensions.Caching.StackExchangeRedis的NuGet包版本与ASP.NET Core 6兼容,建议使用2.7.x及以上的稳定版本,避免版本不匹配导致的配置加载异常。

  • 排除缓存键的潜在问题
    虽然错误指向configuration,但仍需确保调用GetStringAsync时传入的cacheKey不为空:

    if (string.IsNullOrWhiteSpace(cacheKey))
    {
        throw new ArgumentNullException(nameof(cacheKey));
    }
    var cachedData = await _distributedCache.GetStringAsync(cacheKey);
    

内容的提问来源于stack exchange,提问作者Bami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:02:18