首页 > 解决方案 > ConfigurationManager.AppSettings return The given key was not present in the dictionary 错误

问题描述

我在 ConfigurationManager.AppSettings 上遇到错误,错误是 The give key was not present in the dictionary

代码:

string userPass = ConfigurationManager.AppSettings["dev_pass"];

标签: c#model-view-controller

解决方案


如果您使用的是经典 ASP.NET,请确保将该密钥添加到web.config的应用程序设置中...

<appSettings>
    <add key="dev_pass" value="THE_VALUE" />
  </appSettings>

如果您使用的是 ASP.NET Core,请确保您遵循 ASP.NET Core 的指南从appsettings.json. 假设您appsettings.json的配置如下...

{
    "AppSettings": {
        "dev_pass": "THE VALUE"
    }
}

然后创建这个类...

public class AppSettings
{
    public string dev_pass{ get; set; }
}

然后将其配置为服务...

public void ConfigureServices(IServiceCollection services)
{  
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

推荐阅读