在命名空间“System.Configuration”中找不到类型名称“ConfigurationManager”。此类型已转发

The type name 'ConfigurationManager' could not be found in the namespace 'System.Configuration'. This type has been forwarded

提问人:James Garrett 提问时间:2/10/2021 最后编辑:James Garrett 更新时间:2/11/2021 访问量:9215

问:

我在使用 Visual Studio 2019 的 .NET 5.0 项目中收到了此错误(在社区/学生版和专业版上尝试过)。

“在命名空间'System.Configuration'中找不到类型名称'ConfigurationManager'。此类型已转发...”

我发现的许多答案都说您需要添加“using System.Configuration;”,以及通过 Project -> Add Reference 添加程序集命名空间作为引用。这个答案对我不起作用,因为“项目”选项卡中没有“引用”文件夹或任何“添加引用”选项。 “引用管理器”中也没有“程序集”选项卡。仅限“项目”、“共享项目”、“COM”和“浏览”。

如何添加 System.Configuration 作为引用,以便使用 ConfigurationManager?

ASP.NET 核心 visual-studio-2019 配置管理器 asp.net-core-5.0 system.configuration

评论


答:

4赞 James Garrett 2/10/2021 #1

编辑:尽管此答案可能会消除错误,但这不是“正确”的答案,因为 .NET 5 不支持 ConfigurationManager。其他答案最好地解释了这一点。

在 Visual Studio 2019 中,单击顶部的“工具”选项卡。

工具 -> NuGet 包管理器 -> 管理解决方案的 NuGet 包...

搜索“System.Configuration.ConfigurationManager”。

将其安装到您的项目中,错误应该消失了。

评论

0赞 Abhishek Kumar 2/10/2021
这适用于 .NET 5 以下的项目,也不适用于 .NET Core 项目
0赞 James Garrett 2/10/2021
@AbhishekKumar 感谢您的回复。我在 .NET 5 项目中执行此操作,这是不好的做法吗?更具体地说,我正在创建一个 Web 应用程序,并且我正在使用旧版 API 中的类,并且在该类中使用了“ConfigurationManager.AppSettings[”installerbaseurl“]”。我还没有测试使用ConfigurationManager的代码,但是错误已经消失,项目构建良好。使用它有什么问题?
0赞 Abhishek Kumar 2/10/2021 #2

.NEt 5 dosent 使用旧的 ConfigurationManager,您需要从 json 中读取

    public IConfiguration Configuration { get; set; }
    public Startup(IHostingEnvironment environment) 
    {
      Configuration = new Configuration()
                          .AddJsonFile("config.json");
    }
    
    
    var options = ConfigurationBinder.Bind<AppSettings>(Configuration); 
    Console.WriteLine(options.SomeSetting);

欲了解更多信息,请参阅 GitHub.com/aspnet/Options/test/Microsoft.Extensions.Options.Test/OptionsTest.cs

1赞 GlennSills 2/10/2021 #3

System.Configuration.ConfigurationManager 在 .NET 5 中不受支持。请参阅此处,了解如何将具有 web.config 文件的应用迁移到 .NET Core 模式迁移配置

虽然可以在 .NET 5 应用程序中使用 System.Configuration.Configuration 管理器,但这是一个坏主意。该框架已将新内容与应用程序启动集成在一起,如果您不使用它,您将使自己工作更多。较新的配置模式更易于使用并部署到多个环境中。如果想要移植到 .NET 5 的现有 .NET 经典应用,请按照上面的文档进行操作。如果这是一个新应用程序,请查看 Microsoft.Extensions.Configuration 命名空间。