我的配置文件位于:
"~/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>
我怎样才能获得appsettings?
答案 0 :(得分:4)
对于网络应用,您需要使用System.Web.Configuration.WebConfigurationManager
类,而无需设置绝对路径。
var web=System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration("~/admin/web.config");
String appValue=web.AppSettings.Settings["key"].Value;
答案 1 :(得分:0)
如果您正在寻找向Web.config添加一些内容,然后从代码中读取它。 您需要的是 Web.config中的自定义配置部分
看这里: How do I define custom web.config sections with potential child elements and attributes for the properties? 和这里: Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com