【问题标题】:How to use appsettings value in section property of web.config如何在 web.config 的部分属性中使用 appsettings 值
【发布时间】:2020-02-14 13:02:47
【问题描述】:

我想在 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" />

所以基本上我不想将属性configuration 硬编码为127.0.0.1:6379,我想将其设置为

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

这可能吗?

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

【问题讨论】:

  • 我认为配置本身没有办法。如果您使用像 Octopus 这样的第三方工具来执行部署,您可以使用这样的参数执行配置更新,在这种情况下,两个位置将具有相同的占位符,以替换为 Octopus 中定义的单个值。不过,这可能对本地开发构建并没有真正的帮助。

标签: c# asp.net asp.net-web-api nhibernate


【解决方案1】:

配置不是动态的。但是你可以使用WebConfigurationManager 来操作它。

这种方法可以帮助您,来自reference

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();

【讨论】:

  • 抛开这比在配置中两次添加 IP 地址要复杂得多的事实,它真的有效吗?我希望在创建应用程序域时读取 Nhibernate 配置,这意味着之后的更改不会影响已经生成的 Nhibernate 实例。你知道是不是这样吗?
  • 你绝对是对的,同意你的看法。我的回答增加了更多的复杂性,我们可以说它更像是解决方法。但这可能会有所帮助..
猜你喜欢
  • 2012-06-17
  • 2011-08-26
  • 1970-01-01
  • 2012-03-24
  • 2011-12-30
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 2017-02-17
相关资源
最近更新 更多