其他分享
首页 > 其他分享> > web.config的configSections节点

web.config的configSections节点

作者:互联网

原文链接:http://www.cnblogs.com/ToughGuy/p/3485984.html

configSections关联的类型在一个进程内只实例化一次。

1、配置文件Web.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration>
    <configSections>
        <section name="flyLogger" type="Fly.Lib.LoggerSectionHandler,DAL.Test1"/><!--注:DAL.Test1是程序集名-->
    </configSections>
    <flyLogger>
        <add name="file" maxSize="5mb"/>
        <add name="test" sendFlag="false"/>
    </flyLogger>
</configuration>
View Code

 

2、关联的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Xml;

namespace Fly.Lib
{
    //配置聚合根
    public class LoggerConfiguration
    {
        //此测试用于存储配置数据的集合
        private Hashtable myRegionConfig = new Hashtable();
        public Hashtable MyRegionConfig
        {
            get { return myRegionConfig; }
        }

        //获取配置聚合根对象
        public static LoggerConfiguration GetConfig()
        {
            //ConfigurationSettings.GetConfig已过时,使用System.Configuration.ConfigurationManager。
            //首次ConfigurationManager.GetSection("flyLogger")时,将调用LoggerSectionHandler获得对象,后续则直接返回对象。
            return (LoggerConfiguration)System.Configuration.ConfigurationManager.GetSection("flyLogger");
        }

        //加载配置信息,将信息写入集合
        internal void LoadValuesFrom(XmlNode xmlNode)
        {
            foreach (XmlNode item in xmlNode.ChildNodes)
            {
                myRegionConfig.Add(item.Attributes[0].Value, item.Attributes[1].Value);
            }
        }
    }

    //HttpHandler初始化配置(一个进程只初始化一次)。
    internal class LoggerSectionHandler : IConfigurationSectionHandler
    {
        //该方法只被调用一次(在ConfigurationManager.GetSection("flyLogger")首次调用时该方法被调用)。
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            //初始化配置信息
            LoggerConfiguration loggerConfiguration = new LoggerConfiguration();
            loggerConfiguration.LoadValuesFrom(section);
            return loggerConfiguration;
        }
    }
}
View Code

 


3、测试

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Fly.Lib;

namespace DAL.Test1
{
    [TestClass]
    public class ConfigSectionTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var hashtb = LoggerConfiguration.GetConfig().MyRegionConfig;
            foreach (var item in hashtb.Keys)
            {
                Console.WriteLine(string.Format("key={0},value={1}", item, hashtb[item]));
            }
        }
    }
}
View Code

 

小小技巧,可发挥无穷威力!

有了它,更方便创建自己的插件哦!

 

 

2016/5/19新:

1Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细消息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="webConfig" type="xcyOA.Models.WebConfigSectionHandler,xcyOA"/>
  </configSections>
  <webConfig>
    <add name="Attr1" value="889" type="int"/>
    <add name="Attr2" value="150" type="string"/>
    <add name="Attr3" value="false" type="bool"/>
    <add name="Attr4" value="1,3,5,6,7" type="list_int"/>
    <add name="Attr5" value="金戒指,铜戒指" type="list_string"/>
    <add name="UserInfo" value="/Config/UserInfo.xml" type="xcyOA.Models.UserInfo"/>
    <add name="UserInfos" value="/Config/UserInfos.xml" type="list,xcyOA.Models.UserInfo"/>
  </webConfig>
</configuration>
View Code

2C#

/// <summary>
    /// Author:Fly 
    /// Date:2016/05/19
    /// </summary>
    public class WebConfigSectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            return WebConfig.Init(section);
        }
    }

 /// <summary>
    /// Author:Fly 
    /// Date:2016/05/19
    /// </summary>
    public partial class WebConfig
    {
        static WebConfig()
        {
            System.Configuration.ConfigurationManager.GetSection("webConfig");
        }

        internal static object Init(XmlNode xmlNode)
        {
            foreach (XmlNode item in xmlNode.ChildNodes)
            {
                var name = item.Attributes["name"].Value;
                var valAttr = item.Attributes["value"];
                var type = item.Attributes["type"];
                Object val = valAttr.Value;//string
                if (type != null && valAttr != null && val != null)
                {
                    switch (type.Value)
                    {
                        case "int":
                            val = Convert.ToInt32(val);//int
                            break;
                        case "bool":
                            val = Convert.ToBoolean(val);//bool
                            break;
                        case "list_int"://List<int>
                            val = val.ToString().Split(',').Select(m => Convert.ToInt32(m)).ToList<int>();
                            break;
                        case "list_string"://List<string>
                            val = val.ToString().Split(',').Select(m => m).ToList<string>();
                            break;
                        case "string":
                            break;
                        default://对象、泛型集合
                            Type objType;
                            if (type.Value.Contains("list,"))
                            {
                                //泛型集合
                                var clsTypeStr = type.Value.Replace("list,", "");
                                objType = Type.GetType(clsTypeStr);
                                objType = typeof(List<>).MakeGenericType(objType);
                            }
                            else
                            {
                                //对象
                                objType = Type.GetType(type.Value);
                            }
                            var path = Path.Combine(Directory.GetCurrentDirectory(), "../" + val.ToString());
                            val = Serialize(objType, path);
                            break;
                    }
                }
                var prop = typeof(WebConfig).GetProperty(name);
                prop.SetValue(typeof(WebConfig), val, null);
            }
            return typeof(WebConfig);
        }

        private static object Serialize(Type type, string filename)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }

    /// <summary>
    /// Author:Fly 
    /// Date:2016/05/19
    /// </summary>
    public partial class WebConfig
    {
        public static int Attr1 { get; set; }
        public static string Attr2 { get; set; }
        public static bool Attr3 { get; set; }
        public static IList<int> Attr4 { set; get; }
        public static IList<string> Attr5 { set; get; }
        public static UserInfo UserInfo { get; set; }
        public static IList<UserInfo> UserInfos { get; set; }
    }

    public class WebConfigTest
    {
        public void MyTestMethod()
        {
            Console.WriteLine(WebConfig.Attr1);
            Console.WriteLine(WebConfig.Attr2);
            Console.WriteLine(WebConfig.Attr3);
            Console.WriteLine(JSONhelper.ToJson(WebConfig.Attr4));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.Attr5));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.UserInfo));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.UserInfos));
        }
    }


    public class UserInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public List<string> Features { get; set; }
        public UserInfoEx UInfoEx { get; set; }
        public List<UserInfoEx> UInfoExs { get; set; }
    }

    public class UserInfoEx
    {
        public string Var1 { get; set; }
        public string Var2 { get; set; }
    }
View Code

Test:

    public class WebConfigTest
    {
        public void MyTestMethod()
        {
            Console.WriteLine(WebConfig.Attr1);
            Console.WriteLine(WebConfig.Attr2);
            Console.WriteLine(WebConfig.Attr3);
            Console.WriteLine(JSONhelper.ToJson(WebConfig.Attr4));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.Attr5));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.UserInfo));
            Console.WriteLine(JSONhelper.ToJson(WebConfig.UserInfos));
        }

        public void MyTestMethod2()
        {
            List<UserInfo> users = new List<UserInfo>();
            users.Add(new UserInfo { Id = 555 });
            users.Add(new UserInfo { Id = 666 });
            users.Add(new UserInfo { Id = 777 });
            users.Add(new UserInfo { Id = 888 });

            var fs = new FileStream("D:/test.xml", FileMode.Create);
            XmlSerializer serializer = new XmlSerializer(typeof(List<UserInfo>));
            serializer.Serialize(fs, users);
            fs.Close();
        }
    }
View Code

3xml

/Config/UseInfo.xml

<?xml version="1.0" encoding="utf-8" ?>
<UserInfo>
  <Id>15</Id>
  <Name>李四</Name>
  <Age>25</Age>
  <UInfoEx>
    <Var1>子对象属性1。</Var1>
  </UInfoEx>
  <UInfoExs>
    <UserInfoEx>
      <Var1>1子对象集合属性1。</Var1>
    </UserInfoEx>
    <UserInfoEx>
      <Var1>2子对象集合属性1。</Var1>
      <Var2>2子对象集合属性2。</Var2>
    </UserInfoEx>
    <UserInfoEx>
      <Var1>3子对象集合属性1。</Var1>
    </UserInfoEx>
  </UInfoExs>
</UserInfo>
View Code

/Config/UseInfos.xml

<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <UserInfo>
    <Id>555</Id>
    <Age>0</Age>
  </UserInfo>
  <UserInfo>
    <Id>666</Id>
    <Age>0</Age>
  </UserInfo>
  <UserInfo>
    <Id>777</Id>
    <Age>0</Age>
  </UserInfo>
  <UserInfo>
    <Id>888</Id>
    <Age>0</Age>
  </UserInfo>
</ArrayOfUserInfo>
View Code

 

 源码地址:微云/OpenSource/SectionTest.rar

转载于:https://www.cnblogs.com/ToughGuy/p/3485984.html

标签:web,set,Console,get,configSections,System,WebConfig,config,public
来源: https://blog.csdn.net/weixin_30885111/article/details/99121343