65.9K
CodeProject 正在变化。 阅读更多。
Home

如何为 ASP.NET 构建自定义 XML 配置文件(非 web.config)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (8投票s)

2009年3月31日

CPOL

1分钟阅读

viewsIcon

48338

downloadIcon

495

如何为 ASP.NET 构建自定义 XML 配置文件(非 web.config)

引言

在 ASP.NET 社区中经常被问到的问题是“如何为 ASP.NET 构建自定义 XML 配置文件”或“如何在 ASP.NET 中使用我自己的配置文件”。今天我们一起来实现它。

如果想使用自定义配置设置,如果你的 .NET 版本是 1.x,你可以继承 IConfigurationSectionHandler。如果你的 .NET 版本是 2.0,你也可以继承 ConfigurationSection

如果你想将你的配置设置存储在另一个文件(不是Web.config),你可以使用一些可序列化的类来将类序列化到 XML 文件/从 XML 文件反序列化,并将其推送到 ASP.NET 缓存。当文件被修改时,CONFIG 实例会立即改变。

本文包含哪些内容?

如何使用 XML/CONFIG 文件配置应用程序,而不是web.config

Using the Code

一个演示自定义配置文件,例如这个,可以设置你的站点 URL 和主题名称。

<?xml version="1.0"?>
<websiteConfig>
  <siteUrl><![CDATA[http://huobazi.aspxboy.com/]]></siteUrl>
  <themeConfig defaultTheme="Red">
    <theme name="Blue" />
    <theme name="Red" />
    <theme name="Black" />
  </themeConfig>
</websiteConfig>

我们想将其存储在我们自己的配置文件中,而不是web.config
.NET 提供了一个很棒的功能,那就是序列化/反序列化。我们可以使用一个可序列化的类,并可以从我们的 XML 配置文件中对其进行反序列化。

namespace Huobazi.XiaHouWeni.CSDN.TestWebapplication
{
    [XmlRoot( "websiteConfig" )]//Here is a serializable attribute
    public class WebsiteConfiguration
    {
        [XmlElement("siteUrl")]//Here is a serializable attribute
        public string SiteUrl { get; set; }
        [XmlElement( "themeConfig" )]//Here is a serializable attribute
        public ThemeConfig ThemeConfig { get; set; }
    }
}

用于主题设置的其他类

public class ThemeConfig
    {
        [XmlAttribute( "defaultTheme" )]//Here is a serializable attribute
        public string DefaultThemeName { get; set; }
        [XmlElement( "theme" )]//serializable attribute
        public ThemeCollection Themes { get; set; }
        private Theme DefaultTheme
        {
            get { return Themes[DefaultThemeName]; }
        }
    }
    public class Theme
    {
        [XmlAttribute( "name" )]//serializable attribute
        public string Name { get; set; }
    }
    public class ThemeCollection : KeyedCollection<string, Theme>
    {
        protected override string GetKeyForItem(Theme item)
        {
            return item.Name;
        }
    }

然后我们编写一个辅助类来从 XML 配置文件加载设置,并将其插入到 ASP.NET 缓存中。

internal sealed class ConfigLoader
    {
        private ConfigLoader() { }
        public static T LoadConfig<T>() where T : class
        {
            return LoadConfig<T>( null );
        }
        public static T LoadConfig<T>(string fileName) where T : class
        {
            if ( string.IsNullOrEmpty( fileName ) )
            {
                fileName = HttpContext.Current.Server.MapPath
			( string.Concat( "~/", typeof( T ).Name ,".config") );
            }
            string cacheKey = fileName;
            T configObj =  HttpRuntime.Cache[cacheKey] as T;
            if ( configObj == null )// Here we try populate the config from cache
            {
                configObj = LoadFromXml<T>( fileName );
                // insert the config instance into cache use CacheDependency
                HttpRuntime.Cache.Insert( cacheKey, configObj, 
			new System.Web.Caching.CacheDependency( fileName ) );
            }
            return configObj;
        }
        private static T LoadFromXml<T>(string fileName) where T : class
        {
            FileStream fs = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer( typeof( T ) );
                fs = new FileStream( fileName, FileMode.Open, FileAccess.Read );
                return (T)serializer.Deserialize( fs );
            }
            catch ( Exception ex )
            {
                return null;
            }
            finally
            {
                if ( fs != null )
                {
                    fs.Close( );
                }
            }
        }

一个 ConfigManager 类

public static class ConfigManager
{
    public static WebsiteConfiguration WebSitConfig
    {
        get
        {
            return ConfigLoader.LoadConfig<WebsiteConfiguration>( );
        }
    }
}

如何使用

this.txtSiteUrl.Text = ConfigManager.WebSitConfig.SiteUrl;
this.txtCurrentThemeName.Text = ConfigManager.WebSitConfig.ThemeConfig.DefaultThemeName;
this.themeGrid.DataSource = ConfigManager.WebSitConfig.ThemeConfig.Themes;
this.themeGrid.DataBind( );
© . All rights reserved.