首页 > 解决方案 > 如何在 web.config 的部分属性中使用 appsettings 值

问题描述

我想在 web.cofig 的用户定义部分中使用 appsettings 值。

<coredistributedcache factory-class="NHibernate.Caches.CoreDistributedCache.Redis.RedisFactory,NHibernate.Caches.CoreDistributedCache.Redis">
    <properties>
      <property name="configuration">127.0.0.1:6379</property>
    </properties>
  </coredistributedcache>

我已经像这样在appsetting中定义了配置值

<add key="RedisServer" value="127.0.0.1:6379" />

所以基本上我不想将属性硬编码configuration127.0.0.1:6379,我想将它设置为

<property name="configuration">{{RedisServer}}</property>

这甚至可能吗?

或者有没有其他方法可以避免重复?

标签: c#asp.netasp.net-web-apinhibernate

解决方案


配置不是动态的。但是,您可以使用WebConfigurationManager它来操纵它。

这种方法可以帮助您,从参考

var configFile = WebConfigurationManager.OpenWebConfiguration("~");
ClientSettingsSection section = (ClientSettingsSection)configFile.SectionGroups["applicationSettings"].Sections[0];
var value = section.Settings;
SettingElement settingElement = new SettingElement();
SettingValueElement settingValueElement = new SettingValueElement();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("applicationSettings");
var valuenode = nodeList[0].SelectNodes("coredistributedcache/properties/property")[0];
var oldValue = valuenode.InnerText;
valuenode.InnerText = "New Value1";
settingValueElement.ValueXml = valuenode;
settingElement.Value = settingValueElement;
value.Clear();
value.Add(settingElement);
configFile.Save();

推荐阅读