C# 如何使用ConfigurationManager打开配置文件应用程序设置?

C# 如何使用ConfigurationManager打开配置文件应用程序设置?,c#,asp.net,web-config,configurationmanager,C#,Asp.net,Web Config,Configurationmanager,我的配置文件位于此处: "~/Admin/Web.config" 我尝试通过以下代码打开它,但没有成功: var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config"); var configMap = new ConfigurationFileMap(physicalFilePath); var configuration = ConfigurationManager.OpenMappedMach

我的配置文件位于此处:

"~/Admin/Web.config"
我尝试通过以下代码打开它,但没有成功:

var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
appsettings行运行时,会抛出以下错误消息:

Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
我的Web.Config如下所示:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <appSettings>
    <add key="AdminUsername" value="Test1"/>
    <add key="AdminPassword" value="Test2"/>
  </appSettings>
  <connectionStrings></connectionStrings>
</configuration>


如何获取应用程序设置?

如果您想在Web.config中添加一些内容,然后从代码中读取这些内容。 您需要的是Web.config中的自定义配置部分

看这里: 在这里:
对于web应用程序,您需要使用类,而无需设置绝对路径

var web=System.Web.Configuration.WebConfigurationManager
          .OpenWebConfiguration("~/admin/web.config");

String appValue=web.AppSettings.Settings["key"].Value;

访问其AppSettings属性时出现此错误:无法将“System.Configuration.DefaultSection”类型的对象强制转换为“System.Configuration.AppSettingsSection”类型。如何打开.net core AppSettings.json?