第一部分:Web.config如何定義configSections
建立Test.Demo1類庫,默認情況下,此類庫的默認屬性中,程序集名稱爲:Test.Demo1,默認命名空間爲:Test.Demo1.
此類庫生成的Dll相應的爲Test.Demo1.dll和Test.Demo1.pdb.
Demo02.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace Test.SectionDemo
{
/// <summary>
/// 自定義Section
/// </summary>
public class SectionHandle : ConfigurationSection
{
[ConfigurationProperty("users", IsRequired = true)]
public SectionElement Users
{
get
{
return (SectionElement)this["users"];
}
}
}
}
Web.config
<?xml version="1.0"?>
<!--
有關如何配置 ASP.NET 應用程序的詳細信息,請訪問
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<section name="SectionHandle" type="Test.SectionDemo.SectionHandle,Test.Demo1"/>
</configSections>
<SectionHandle>
<users username="kevin" password="123"></users>
</SectionHandle>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
此處,type=“Test.SectionDemo.SectionHandle"來自Demo2.cs的類定義。和默認命名空間沒有關係。
但是Test.Demo1就來自“程序集名稱爲:Test.Demo1”
Element.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace Test.SectionDemo
{
/// <summary>
/// 自定義Element
/// </summary>
public class SectionElement : ConfigurationElement
{
/// <summary>
/// 用戶名
/// </summary>
[ConfigurationProperty("username", IsRequired = true)]
public string UserName
{
get
{
return (string)this["username"];
}
}
/// <summary>
/// 密碼
/// </summary>
[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get
{
return (string)this["password"];
}
}
}
}
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Test.SectionDemo;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SectionHandle mySectionHandle = (SectionHandle)ConfigurationManager.GetSection("SectionHandle");
Response.Write("username:" + mySectionHandle.Users.UserName + "<br/>");
Response.Write("password:" + mySectionHandle.Users.Password + "<br/>");
}
}
運行結果
第二部分:assembly小修改
如果將程序集名稱手動改爲Test.Demo15,默認命名空間也改爲Test.Demo15
此時可以看到Bin中的生成文件變了(Test.Demo15.dll),和程序集名稱保持一致。
那麼Web.config中也要相應的改爲
<section name="SectionHandle" type="Test.SectionDemo.SectionHandle,Test.Demo15"/>
類名稱沒有變,只是assembly改變了。默認命名空間改動看上去沒有影響。