第一部分: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改变了。默认命名空间改动看上去没有影响。