文章出處
文章列表
在web.config文件中擁有一個用戶自定義配置節點configSections,這個節點可以方便用戶在web.config中隨意的添加配置節點,讓程序更加靈活(主要用于第三方插件的配置使用)
自定義節點是一個XML格式的數據,我們可以在節點中靈活的配置自己的數據,下面是一個簡單數據的例子
1.先看一下web.config中的配置結構
<configSections>
<section name="modelsection" type="Amy.WebUI.Plugin.ConfigSections.ModelSectionHandler,Amy.WebUI"/>
</configSections>
<modelsection>
<title>測試</title>
<content>測試</content>
</modelsection>
2.為了實現自定義配置節點的解析,我們需要實現接口IConfigurationSectionHandler
public class ModelSectionHandler : IConfigurationSectionHandler
{
/// <summary>
/// 解析配置文件信息
/// </summary>
public object Create(object parent, object configContext, XmlNode section)
{
var json = section.ToJsonByJsonNet().GetJsonValue("modelsection");
return json.ToObjectByJsonNet<ModelConfig>();
}
}
3.ModelConfig類為了防止消耗IO資源,做了一個單例
public class ModelConfig
{
private static ModelConfig instance;
private static readonly object syncObject = new object();
private ModelConfig() { }
public static ModelConfig GetInstance()
{
if (instance == null)
{
lock (syncObject)
{
if (instance == null)
{
instance = (Plugin.ConfigSections.ModelConfig)System.Configuration.ConfigurationManager.GetSection("modelsection");
}
}
}
return instance;
}
public string Title { get; set; }
public string Content { get; set; }
}
4.讀取數據,很簡單及類的靜態方法調用就OK;var config = Plugin.ConfigSections.ModelConfig.GetInstance();
文章列表
