我目前在我的 Web.config 中有一些配置变量,例如:
<appSettings>
<add key="RecipientEmailForNotifications" value="asdf@sdf.com" />
<add key="NotifyNewEntries" value="true" />
<!-- etc... -->
</appSettings>
我有一个 View ,管理员用户可以在线更改此值,例如。
/Admin/Configuration/
Recipient email for notifications: [___________]
Notify new entries: [x] Yes
[SAVE]
但是这种方法有两个问题:
- 每次我部署 web.config 时,我都会覆盖那些在线保存的值
- 每次网络应用重启(因为网络应用在没有事件时自然停止),这些在线保存的值被重置为上次部署时的原始值
所以问题是: 实现必须保留配置变量这一目标的最佳方法是什么?
我认为使用表格不是很自然,但我可能错了(请解释原因)。
此外,读取值时使用应用程序设置非常方便:
ConfigurationManager.AppSettings["RecipientEmailForNotifications"]
相对于使用数据库,
db.SomeConfigurationTable.SingleOrDefault(.....)
最佳答案
我会结合使用数据库存储和缓存。
如果您在单个网络服务器上,您可以将设置存储在过程缓存中。如果您在网络农场中,您可以查看诸如 couchbase(免费内存缓存)或 azure 之类的东西。 .
在应用程序启动时预热缓存可能是有意义的。那就是从你的数据库中读取设置并填充你的缓存。
另一种流行的方法是进行 Get 调用,首先检查缓存并在缓存为空时填充缓存,例如
public string Get(string key, Func<string> getItemCallback)
{
var item = Cache.Get(key) as string;
if (item == null)
{
item = db.SomeConfigurationTable.SingleOrDefault(key);
Cache.Store(key, item);
}
return item;
}
不要忘记在更新设置时您需要爆破缓存。
关于c# - 替代 web.config 中的 appsettings(需要持久性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22151658/