.NET 6/.NET Core中app.config的system.net节点报未识别异常
报错信息
System.Configuration.ConfigurationErrorsException: 'Configuration system failed to initialize'
内部异常:
ConfigurationErrorsException: Unrecognized configuration section system.net
产生原因
.NET 6属于.NET 5+跨平台版本体系,项目中引用的System.Configuration.ConfigurationManager NuGet包是为兼容老式App.config配置模式提供的兼容层,默认仅内置appSettings、connectionStrings等少数基础配置节的解析逻辑,不会自动注册.NET Framework时代默认内置的system.net等传统配置节处理程序。配置文件中直接添加未声明的<system.net>节点时,配置系统初始化阶段无法识别该节点,直接抛出初始化失败异常。
复现相关代码与配置
- 程序测试代码
using System.Configuration; string? bogus = ConfigurationManager.AppSettings["Bogus"]; Console.WriteLine($"Hello, {bogus}!");
- 触发异常的原app.config配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.net> <settings> <servicePointManager expect100Continue="false" useNagleAlgorithm="false" /> </settings> </system.net> <appSettings> <add key="Bogus" value="Bogus" /> </appSettings> </configuration>
- 原项目csproj配置
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" /> </ItemGroup> </Project>
修复方法
在<configuration>节点的第一个子元素位置添加<configSections>节点,手动声明system.net配置节对应的解析类型即可。注意configSections必须放在所有其他配置节点的最前面,否则仍会触发配置错误。
修正后的完整app.config内容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- configSections必须为configuration下第一个子节点 --> <configSections> <sectionGroup name="system.net" type="System.Net.Configuration.NetSectionGroup, System.Configuration.ConfigurationManager"> <section name="settings" type="System.Net.Configuration.SettingsSection, System.Configuration.ConfigurationManager"/> </sectionGroup> </configSections> <system.net> <settings> <servicePointManager expect100Continue="false" useNagleAlgorithm="false" /> </settings> </system.net> <appSettings> <add key="Bogus" value="Bogus" /> </appSettings> </configuration>
替换配置后重新运行程序,即可正常加载system.net下的相关配置,不会再抛出初始化异常。
内容的提问来源于stack exchange,提问作者Cosmin
相关产品推荐
相关产品推荐

