一步步開發自己的博客 .NET版(11、Web.config文件的讀取和修改)


Web.config的讀取

對於Web.config的讀取大家都很屬性了。平時我們用得比較多的就是appSettings節點下配置。如:

我們對應的代碼是:

= ConfigurationManager.AppSettings[“OAuth_QQ_ClientId”]; 
= ConfigurationManager.AppSettings[“OAuth_QQ_CallbackUrl”];
= ConfigurationManager.AppSettings[“OAuth_QQ_ClientScrert”];
= ConfigurationManager.AppSettings[“OAuth_Sina_ClientId”];
= ConfigurationManager.AppSettings[“OAuth_Sina_ClientScrert”];
= ConfigurationManager.AppSettings[“OAuth_Sina_CallbackUrl”];
........

 是的,很簡單、很方便、很清晰。可以總感覺缺少那么一點“面向對象”的感覺。少還無所謂,如果幾十個上百個呢?我們是不是可以考慮分類定義,如下:

 <!--自定義配置-->
  <customCon>
    <!--郵件配置-->
    <mail mailPwd="" mailHost="" mailFrom="" />
    <!--QQ登陸-->
    <oAuthQQ OAuth_QQ_ClientId="" OAuth_QQ_ClientScrert="" OAuth_QQ_CallbackUrl="haojima.net/hi_login.html" />
    <!--新浪登錄-->
    <oAuthSina OAuth_Sina_ClientId="" OAuth_Sina_ClientScrert="" OAuth_Sina_CallbackUrl="haojima.net/hi_login.html" />
  </customCon>

 可是,你會發現 customCon 編輯器不認,因為這是我自己定義的一個,那如何是好?如下:(申明自定義標簽

如此,是不是感覺分類更清楚了?可是問題又來了,那我們怎么讀取自定義標簽里面的值呢?

首先:(注意:需要繼承ConfigurationSection

/// <summary>
    /// 自定義配置
    /// </summary>
    public class CustomCon : ConfigurationSection
    {
        /// <summary>
        /// 郵箱設置
        /// </summary>
        [ConfigurationProperty("mail", IsRequired = true)]
        public MailElement Mail
        {
            get { return (MailElement)this["mail"]; }
        }

        /// <summary>
        /// qq登錄
        /// </summary>
        [ConfigurationProperty("oAuthQQ", IsRequired = true)]
        public OAuthQQElement OAuthQQ
        {
            get { return (OAuthQQElement)this["oAuthQQ"]; }
        }

        /// <summary>
        /// 新浪登錄
        /// </summary>
        [ConfigurationProperty("oAuthSina", IsRequired = true)]
        public OAuthSinaElement OAuthSina
        {
            get { return (OAuthSinaElement)this["oAuthSina"]; }
        }
    } 

然后MailElement、OAuthQQElement、OAuthSinaElement 分別具體定義:

 #region MailElement(郵箱)
    public class MailElement : ConfigurationElement
    {
        /// <summary>
        /// 發件人密碼
        /// </summary>
        [ConfigurationProperty("mailPwd", IsRequired = true)]
        public string Pwd
        {
            get { return this["mailPwd"].ToString(); }
            set { this["mailPwd"] = value; }
        }

        /// <summary>
        /// SMTP郵件服務器
        /// </summary>
        [ConfigurationProperty("mailHost", IsRequired = true)]
        public string Host
        {
            get { return this["mailHost"].ToString(); }
            set { this["mailHost"] = value; }
        }

        /// <summary>
        ///發件人郵箱
        /// </summary>
        [ConfigurationProperty("mailFrom", IsRequired = true)]
        public string From
        {
            get { return this["mailFrom"].ToString(); }
            set { this["mailFrom"] = value; }
        }
    }
    #endregion

    #region OAuthQQElement(QQ)
    public class OAuthQQElement : ConfigurationElement
    {

        [ConfigurationProperty("OAuth_QQ_ClientId", IsRequired = true)]
        public string ClientId
        {
            get { return this["OAuth_QQ_ClientId"].ToString(); }
            set { this["OAuth_QQ_ClientId"] = value; }
        }


        [ConfigurationProperty("OAuth_QQ_ClientScrert", IsRequired = true)]
        public string ClientScrert
        {
            get { return this["OAuth_QQ_ClientScrert"].ToString(); }
            set { this["OAuth_QQ_ClientScrert"] = value; }
        }


        [ConfigurationProperty("OAuth_QQ_CallbackUrl", IsRequired = true)]
        public string CallbackUrl
        {
            get { return this["OAuth_QQ_CallbackUrl"].ToString(); }
            set { this["OAuth_QQ_CallbackUrl"] = value; }
        }
    }
    #endregion

    #region OAuthSinaElement(新浪)
    public class OAuthSinaElement : ConfigurationElement
    {

        [ConfigurationProperty("OAuth_Sina_ClientId", IsRequired = true)]
        public string ClientId
        {
            get { return this["OAuth_Sina_ClientId"].ToString(); }
            set { this["OAuth_Sina_ClientId"] = value; }
        }


        [ConfigurationProperty("OAuth_Sina_ClientScrert", IsRequired = true)]
        public string ClientScrert
        {
            get { return this["OAuth_Sina_ClientScrert"].ToString(); }
            set { this["OAuth_Sina_ClientScrert"] = value; }
        }


        [ConfigurationProperty("OAuth_Sina_CallbackUrl", IsRequired = true)]
        public string CallbackUrl
        {
            get { return this["OAuth_Sina_CallbackUrl"].ToString(); }
            set { this["OAuth_Sina_CallbackUrl"] = value; }
        }
    }
    #endregion
View Code

到現在為止,我們在代碼層面已經建立和config一一對應的關聯了。下面我們來取值:

 CustomCon custom = (CustomCon)ConfigurationManager.GetSection("customCon");
 var url = custom.OAuthQQ.CallbackUrl;//獲取值
 var id = custom.OAuthQQ.ClientId;//獲取值
 //、、、、、

如此是不是甚爽,比原先的 appSettings 更有“對象”的感覺了吧。且,當你配置過多的時候分類也更加清晰!

Web.config的寫入

 對於Web.config的寫入需求一般很少,多數都只是讀取。那為什么我這里要說寫入呢?因為好多人問我“這個博客系統的數據庫在哪里?”,每次都解釋的'不亦樂乎',"這個是coder first根據代碼生成數據庫",后來次數多了實在受不了了。考慮着,是否可以做個引導頁面,初次使用的時候提示設置數據庫和郵箱什么的(這樣的話對於沒有編程基礎的人搭建自己的博客系統也降低了門檻)。

第一次啟動程序的時候檢查數據庫連接,沒有就進入引導頁面,設置。(這個過程都不用去編輯Web.config文件了

好了,看了上面的效果圖我們繼續來看是怎么把數據寫入到Web.config文件的吧。

其實很簡單,稍微改下上面代碼:

改成通過 WebConfigurationManager.OpenWebConfiguration 來讀取代碼就可以編輯了。不過不要忘了 config.Save(); 才會真正更新到Web.config里面去。

到這里還只能修改我們自定義的節點數據。我們最最主要的是想更新數據庫連接,請看下面對數據庫連接的操作:

/// <summary>
/// 修改數據庫連接
/// </summary>
/// <param name="key"></param>
/// <param name="connectionString"></param>
/// <param name="providerName"></param>
public static void SetConnectionString(string key, string connectionString, string providerName = "System.Data.SqlClient")
{
    ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
    if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此節點,則添加  
    {
        ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString, providerName);
        connectionSetting.ConnectionStrings.Add(connectionStringSettings);
    }
    else//如果存在此節點,則修改  
    {
        connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
        connectionSetting.ConnectionStrings[key].ProviderName = providerName;
    }
    config.Save();
}

其實,細看和我們上面的代碼大同小異。(只是把我們自定義的類改成了 ConnectionStringsSection .net默認的連接對象) 

 

一步步搭建自己的博客

好了,以上都是胡說八道。

主要是說下思路,大家自由發揮。感謝您的閱讀,希望對您有一點點作用!

文章首鏈:http://www.cnblogs.com/zhaopei/p/5677053.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM