WebConfig自訂節點並讀取

來源:互聯網
上載者:User

標籤:style   blog   http   color   get   2014   

  最近是遇到了一個需求,需要自訂WebConfig節點,然後進行讀取,網上有很多部落格,寫的非常好,但是筆者在實現的過程中還是遇到了點問題,現在寫一篇文章來總結下。

首先推薦大家看http://www.cnblogs.com/huc87/archive/2009/05/06/1450981.html,筆者就是照著這篇blog來完成自己的demo。先把demo貼出來

大家一定要注意ConfigSections一定要寫在Configuration裡面第一個元素的位置,然後有底線的地方,一定要把命名空間寫全,包括程式集名。其實注意著幾點就ok了,剩下的照著上面推薦的部落格完全可以完成。

下面是完整的Demo

App.Config

<?xml version="1.0" encoding="utf-8" ?><configuration>  <configSections>    <sectionGroup name="JobList">      <section name="Job" type="Demo10.MyConfigHandler,Demo10"/>    </sectionGroup>  </configSections>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  </startup>  <JobList>    <Job>      <add key="Url" value="http://www.baidu.com" />      <add key="Hour" value="10" />      <add key="Minute" value="20"/>    </Job>  </JobList></configuration>

  MyConfigHandler.CS

using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Configuration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo10{    public class MyConfigHandler:IConfigurationSectionHandler    {        public  MyConfigHandler()        {            }        public object Create(object parent, object configContext, System.Xml.XmlNode section)        {            NameValueCollection configs;            NameValueSectionHandler baseHandler=new NameValueSectionHandler();            configs = (NameValueCollection) baseHandler.Create(parent, configContext, section);            return configs;        }    }}
namespace Demo10{    class Program    {        static void Main(string[] args)        {            object o = ((NameValueCollection) ConfigurationSettings.GetConfig("JobList/Job"));            string myWebSiteName = ((NameValueCollection) ConfigurationSettings.GetConfig("JobList/Job"))["Url"];        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.