您的位置:首页 > 其它

Web.config自定义节点

2015-07-13 23:46 423 查看
参考资料:关于ConfigurationManager.GetSection()方法

首先建立一个MVC项目,项目名字叫MvcApp,然后再项目的Models文件夹下创建一个自定义类,这里我创建的这个类取名叫ContactUsSectionHandler.cs,这个类继承自IConfigurationSectionHandler 这个接口。这个类的作用就是用来获取到Web.config配置文件中的这个ContactUs节点的内容

ContactUsSectionHandler.cs类

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

namespace MvcApp.Models
{
    public class ContactUsSectionHandler : IConfigurationSectionHandler
    {
        private XmlNode _sectionNode;
        public XmlNode SectionNode
        {
            get { return _sectionNode; }
        }

        //当调用ConfigurationManager.GetSection("ContactUsSection")方法时,如果某个类继承IConfigurationSectionHandler接口,那么会触发此接口的Create方法,此时ConfigurationManager.GetSection("ContactUsSection")获取到的Web.config配置文件中的ContactUsSection节点就会传递到 Create方法的第三个参数section上。所以此时section中保存的内容就是Web,config配置文件中的ContactUsSection这个节点的内容
        public virtual object Create(object paarnet, object context, XmlNode section)//实现IConfigurationSectionHandler接口中的Create方法
        {
            this._sectionNode = section; //初始化私有成员_sectionNode

            return this; //这个this 其实就是 MvcApp.Models.ContactUsSectionHandler 类的对象。因为我已经在Create方法中将Web.config配置文件中的ContactUsSection这个节点赋值给当前类ContactUsSectionHandler的一个私有属性_sectionNode了。 所以这里这里就可以返回当前类的一个对象啦。
        }

    }
}

接收Web.config配置文件中的这个ContactUsSection节点的类定义好了。下面就来在Web.config里面自定义的ContactUsSection的节点

Web.cofig配置文件

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433   -->

<configuration>
  <configSections >

    <!--既然要自定义一个ContactUsSection节点,就需要先在<configSections></configSections>这个节点里声明一下自定义节点的名称及类型-->
    <!--这个type表示节点的类型是什么,其实就是表明如果你要获取这个节点的时候,用哪个类来保存这个ContactUsSection节点的内容。 我这里是用MvcApp项目下的Models文件夹下的ContactUsSectionHandler类来保存ContactUsSection这个节点的内容。逗号后面的MvcApp是项目名称-->
    <section name="ContactUsSection" type="MvcApp.Models.ContactUsSectionHandler,MvcApp"/>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

  <system.web>

    <httpRuntime targetFramework="4.5" />

    <compilation debug="true" targetFramework="4.5" />

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

  <!--自定义一个ContactUsSection节点-->
  <ContactUsSection>
    
    <ContactUs>
      <SMTP host="smtp.qq.com" port="587" EnableSsl="true" UseDefaultCredentials="">
        <From password="123456" displayname="">12345678910@qq.com</From>
        <To>98765432101@qq.com</To>
        <Cc>mono@163.com</Cc>
        <Bcc></Bcc>

      </SMTP>
      <Subject>wowo.mm.com - #?organization?#</Subject>
      <Template>
        <![CDATA[ 
          <div> 
              First Name: #?firstname?#<br/><br/> 
              Last Name: #?lastname?#<br/><br/> 
              Job Title: #?jobtitle?#<br/><br/> 
              Company Name: #?organization?#<br/><br/> 
              Country: #?country?#<br/><br/> 
              Business Email: <a href='mailto:#?businessemail?#' target='blank'>#?businessemail?#</a><br/><br/> 
              Phone Number: #?phonenumber?#<br/><br/> 
              Area of Interest: #?inquiry?#<br/><br/> 
              Message: #?message?# 
          </div> 
        ]]>

      </Template>
    </ContactUs>
    
    <EmailOverload trigger="500">
      <SMTP host="127.0.0.1" port="25" EnableSsl="" UseDefaultCredentials="">
        <From password="" displayname="NCXM">yes@163.com</From>
        <To>wowo@163.com</To>
      </SMTP>      
      <Subject>警告消息</Subject>
      <Template>
        <![CDATA[ 
       There were over #?trigger?# emails HAHA.<br/><br/> 
       Hour 0 : #?00?#<br/> 
       Hour 1 : #?01?#<br/> 
       Hour 2 : #?02?#<br/> 
       Hour 3 : #?03?#<br/> 
       Hour 4 : #?04?#<br/> 
       Hour 5 : #?05?#<br/> 
       Hour 6 : #?06?#<br/> 
       Hour 7 : #?07?#<br/> 
       Hour 8 : #?08?#<br/> 
       Hour 9 : #?09?#<br/> 
       Hour 10 : #?10?#<br/> 
       Hour 11 : #?11?#<br/> 
       Hour 12 : #?12?#<br/> 
        Hour 13 : #?13?#<br/> 
        Hour 14 : #?14?#<br/> 
        Hour 15 : #?15?#<br/> 
        Hour 16 : #?16?#<br/> 
        Hour 17 : #?17?#<br/> 
        Hour 18 : #?18?#<br/> 
        Hour 19 : #?19?#<br/> 
        Hour 20 : #?20?#<br/> 
        Hour 21 : #?21?#<br/> 
        Hour 22 : #?22?#<br/> 
        Hour 23 : #?23?#<br/> 
        ]]>
      </Template>
    </EmailOverload>
    
    <AdobeTracking>
      <PostUrl>http://ccr.com.drc4.scd.omddtrdc.net/b/ss//88</PostUrl>
      <Template>
        <![CDATA[ 
             <request> 
                  <sc_xml_ver>1.0</sc_xml_ver> 
                  <pageURL>#?cururl2?#</pageURL> 
                  <referrer>#?cururl?#</referrer> 
                  <ipAddress>#?ipaddr?#</ipAddress> 
                  <pageName>home:contact us</pageName> 
                  <channel>contact us</channel> 
                  <events>event44</events> 
                  <contextData> 
                    <crm> 
                      <enquiryType>general</enquiryType> 
                    </crm> 
                  </contextData> 
                  <contextData> 
                    <pageInfo> 
                    <siteName>#?sname?#</siteName> 
                    </pageInfo> 
                  </contextData> 
                  <contextData> 
                    <pageInfo> 
                      <geoRegion>#?georegion?#</geoRegion> 
                    </pageInfo> 
                  </contextData> 
                  <contextData> 
                    <pageInfo> 
                      <leadSource>#?lead?#</leadSource> 
                    </pageInfo> 
                  </contextData> 
                  <contextData> 
                    <crm> 
                      <prospectCountry>#?pcountry?#</prospectCountry> 
                    </crm> 
                  </contextData> 
                  <contextData> 
                    <crm> 
                      <industry>#?selected_subject2?#</industry> 
                    </crm> 
                  </contextData> 
                  <prop75>xml</prop75> 
                  <userAgent>#?useragent?#</userAgent> 
                  <marketingCloudVisitorID>#?mcid?#</marketingCloudVisitorID> 
                  <visitorID>#?analyticsid?#</visitorID> 
                  <reportSuiteID>#?aacoun?#</reportSuiteID> 
             </request>"        
      ]]>        
      </Template>
      
    </AdobeTracking>

    <User>
      <UserInfo name="张三" age="25" Gender="1"/>
      <UserInfo name="李四" age="26" Gender="0"/>
      <UserInfo name="王五" age="28" Gender="1"/>
    </User>
  </ContactUsSection>
</configuration>


接收类,和配置文件都定义好后,看我们如何来使用它

创建Home控制器

using MvcApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            //调用ConfigurationManager.GetSection("ContactUsSection")方法,获取Web.config配置文件中的ContactUsSection节点的内容,
            //注意:Web.config配置文件中的ContactUsSection节点的内容保存在ContactUsSectionHandler类的私有属性_sectionNode中
            //注意:_sectionNode属性的类型是XmlNode类型的,所以它可以保存ContactUsSection节点的内容
            ContactUsSectionHandler section = System.Configuration.ConfigurationManager.GetSection("ContactUsSection") as ContactUsSectionHandler;

            return View();
        }

    }
}




============================================================

好了。我们在看看如何利用ContactUsSection这个节点下的信息或初始化一个类

首先我们在Models文件夹下再创建一个User的类

User类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApp.Models
{
    public class User
    {
        public string Name { get; set; }

        public string Age { get; set; }

        public string Gender { get; set; }

        //在这里类里还可以做很多事情
    }
}

然后再ContactUsSectionHandler.cs 写初始化User类的的代码

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

namespace MvcApp.Models
{
    public class ContactUsSectionHandler : IConfigurationSectionHandler
    {
        private XmlNode _sectionNode;
        public XmlNode SectionNode
        {
            get { return _sectionNode; }
        }

        //当调用ConfigurationManager.GetSection("ContactUsSection")方法时,如果某个类继承IConfigurationSectionHandler接口,那么会触发此接口的Create方法,此时ConfigurationManager.GetSection("ContactUsSection")获取到的Web.config配置文件中的ContactUsSection节点就会传递到 Create方法的第三个参数section上。所以此时section中保存的内容就是Web,config配置文件中的ContactUsSection这个节点的内容
        public virtual object Create(object paarnet, object context, XmlNode section)//实现IConfigurationSectionHandler接口中的Create方法
        {
            this._sectionNode = section; //初始化私有成员_sectionNode

            return this; //这个this 其实就是 MvcApp.Models.ContactUsSectionHandler 类的对象。因为我已经在Create方法中将Web.config配置文件中的ContactUsSection这个节点赋值给当前类ContactUsSectionHandler的一个私有属性_sectionNode了。 所以这里这里就可以返回当前类的一个对象啦。
        }

        //因为ContactUsSection这个节点下面还有其他的子节点,每个子节点都会有独立的功能。现在我们就写个例子

        //获取User这个类的实例,其实获取的是一个List<User>对象
        public List<User> GetUserInstance()
        {
            List<User> list = new List<User>();
            InitializeUser(list);
            return list;
        }

        //初始化User
        public void InitializeUser(List<User> list)
        {
            XmlNode node = null;
            foreach (XmlNode chilNode in _sectionNode)
            {
                //如果子节点的名称为User的这个节点
                if (chilNode.Name.ToLower() == "User".ToLower())
                {
                    node = chilNode;
                    break;
                }
            }

           //遍历User这个节点
            foreach (XmlNode childNode in node.ChildNodes)
            {
                User user = new User();
                user.Name = childNode.Attributes["name"].Value;
                user.Age = childNode.Attributes["age"].Value;
                user.Gender = childNode.Attributes["gender"].Value;
                list.Add(user);
            }
        }

    }
}
写好代码后,我们来Home控制器中来调用

using MvcApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            //调用ConfigurationManager.GetSection("ContactUsSection")方法,获取Web.config配置文件中的ContactUsSection节点的内容,
            //注意:Web.config配置文件中的ContactUsSection节点的内容保存在ContactUsSectionHandler类的私有属性_sectionNode中
            //注意:_sectionNode属性的类型是XmlNode类型的,所以它可以保存ContactUsSection节点的内容
            ContactUsSectionHandler section = System.Configuration.ConfigurationManager.GetSection("ContactUsSection") as ContactUsSectionHandler;

            List<User> user = section.GetUserInstance();

            return View();
        }

    }
}

我们可以看到user这个对象有三项



上面仅仅是举了一个例子而已。当然我们还可以用节点来做很多很多事情


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: