c# - 如何在 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" />
所以基本上我不想将属性硬编码configuration
为127.0.0.1:6379
,我想将它设置为
<property name="configuration">{{RedisServer}}</property>
这甚至可能吗?
或者有没有其他方法可以避免重复?
解决方案
配置不是动态的。但是,您可以使用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();
推荐阅读
- angular - 在 Angular 6 中实施 Paypal
- python-3.x - 如何将加载的 keras 模型的图像保存为 png/jpg?
- angular - 通过按角度 4 中的 enter 键提交表单
- apache-kafka-streams - 如何通过多个StreamListener Spring Cloud Stream和Kafka stream监听多个topic
- laravel-5 - Laravel 访客中间件
- haskell - 好奇为什么进入 StateT monad 转换器返回 a 而不是 (a, s)
- android - 如何将拍摄的照片上传到 phpmadmin?
- python-3.x - 使用 itertools.permutation 时内核死机
- php - 如何将第一个值转换为数组名称php的键
- java - 使用 URL 将图片加载到圆圈 JavaFX 会在 Windows 上出现错误