您可能会考虑的一个选项是创建一个自定义配置部分,您可以在web.config
.
这是我为引用我们的 XSLT 模板而创建的配置部分:
namespace Foo.Web.Applications.CustomConfigurationSections
{
public class XslTemplateConfiguration : ConfigurationSection
{
[ConfigurationProperty("xslTemplates")]
public XslTemplateElementCollection XslTemplates
{
get { return this["xslTemplates"] as XslTemplateElementCollection; }
}
}
public class XslTemplateElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return this["name"] as string; }
set { this["name"] = value; }
}
[ConfigurationProperty("path", IsRequired = true)]
public string Path
{
get { return this["path"] as string; }
set { this["path"] = value; }
}
}
public class XslTemplateElementCollection : ConfigurationElementCollection
{
public XslTemplateElement this[object key]
{
get { return base.BaseGet(key) as XslTemplateElement; }
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "xslTemplate"; }
}
protected override bool IsElementName(string elementName)
{
bool isName = false;
if (!String.IsNullOrEmpty(elementName))
isName = elementName.Equals("xslTemplate");
return isName;
}
protected override ConfigurationElement CreateNewElement()
{
return new XslTemplateElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((XslTemplateElement)element).Name;
}
}
}
您可以在 web.config 中注册此部分,如下所示:
<configSections>
<section name="xslTemplateConfiguration" type="Foo.Web.Applications.CustomConfigurationSections.XslTemplateConfiguration"/>
</configSections>
您可以像这样访问代码中的集合:
var config = WebConfigurationManager.OpenWebConfiguration("/");
if (config.HasFile)
{
var templates = config.GetSection("xslTemplateConfiguration") as XslTemplateConfiguration;
if (templates != null)
{
var templatePath = templates.XslTemplates["PO"].Path;
}
}