zoukankan      html  css  js  c++  java
  • web.config配置详细说明

    (一).Web.Config是以XML文件规范存储,配置文件分为以下格式

        1.配置节处理程序声明
        特点:位于配置文件的顶部,包含在<configSections>标志中。

        2.特定应用程序配置
        特点: 位于<appSetting>中。可以定义应用程序的全局常量设置等信息.

        3.配置节设置
        特点: 位于<system.Web>节中,控制Asp.net运行时的行为.

        4.配置节组
        特点: 用<sectionGroup>标记,可以自定义分组,可以放到<configSections>内部或其它<sectionGroup>标记的内部.

        (二).配置节的每一节
        1.<configuration>节
        根元素,其它节都是在它的内部.
        
         2.<appSetting>节
        此节用于定义应用程序设置项。对一些不确定设置,还可以让用户根据自己实际情况自己设置
        用法:
         I.
            <appSettings>
               <add key="Conntction" value="server=192.168.85.66;userid=sa;password=;database=Info;"/>
            <appSettings>
            定义了一个连接字符串常量,并且在实际应用时可以修改连接字符串,不用修改程式代码.
        II.
            <appSettings>
              <add key="ErrPage" value="Error.aspx"/>
            <appSettings>
            定义了一个错误重定向页面.
        III.

           <appSettings configSource="source/new.xml"/>可以通过新的XML来扩展配置内容。

          new.xml写法为:

           <?xml version="1.0" encoding="utf-8" ?>

            <appSettings>

              <add key="" value="|"/>

            </appSettings>

        3.<compilation>节
        格式:
            <compilation defaultLanguage="c#" debug="true" />
         I.
            default language: 定义后台代码语言,可以选择C#和VB.net两种语言.
         II.
            debug : 为true时,启动aspx调试;为false不启动aspx调试,因而可以提高应用程序运行时的性能。一般程序员在开发时设置为true,交给客户时设置为false.

        4.<customErrors>节
        格式:
            <customErrors mode="RemoteOnly" defaultRedirect="error.aspx"
                <error statusCode="440" redirect="err440page.aspx"/>
                <error statusCode="500" redirect="err500Page.aspx"/>
            />
        I.
            mode : 具有On,Off,RemoteOnly 3种状态。On表示始终显示自定义的信息; Off表示始终显示详细的asp.net错误信息; RemoteOnly表示只对不在本地Web服务器上运行的用户显示自定义信息.
        II.
            defaultRedirect: 用于出现错误时重定向的URL地址. 是可选的
        III.
            statusCode: 指明错误状态码,表明一种特定的出错状态.
        IV.
            redirect:错误重定向的URL.

        5.<globalization>节
        格式:
            <globalization requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" />
        I.
            requestEncoding: 它用来检查每一个发来请求的编码.
        II.
            responseEncoding: 用于检查发回的响应内容编码.
        III.
            fileEncoding: 用于检查aspx,asax等文件解析的默认编码.

        6.<sessionState>节
        格式:
            <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />
        I.
            mode: 分为off,Inproc,StateServer,SqlServer几种状态
        II.
            stateConnectionString :指定Asp.net应用程序存储远程会话状态的服务器名,默认为本机
        III.
            sqlConnectionString: 当用会话状态数据库时,在这里设置连接字符串
        IV.
            Cookieless: 设置为true时,表示不使用cookie会话状态来标识客户; 否则,相反.
        V.
            TimeOut: 用来定义会话状态存储的时间,超过期限,将自动终止会话.

        7.<authentication>节
        格式:
            <authentication mode="Forms">
              <forms name=".ASPXUSERDEMO" loginUrl="Login.aspx" protection="All" timeout="30"/>
              </authentication>
              <authorization>
              <deny users="?"/>
            </authorization>
        I.
            Windows: 使用IIS验证方式
        II.
            Forms: 使用基于窗体的验证方式
        III.
         Passport: 采用Passport cookie验证模式
        IV.
            None: 不采用任何验证方式

         里面内嵌Forms节点的属性涵义:
        I.
            Name: 指定完成身份验证的Http cookie的名称.
        II.
            LoginUrl: 如果未通过验证或超时后重定向的页面URL,一般为登录页面,让用户重新登录
        III.
            Protection: 指定 cookie数据的保护方式.

            可设置为: All None Encryption Validation四种保护方式
                a. All表示加密数据,并进行有效性验证两种方式
                b. None表示不保护Cookie.
                c. Encryption表示对Cookie内容进行加密
                d. validation表示对Cookie内容进行有效性验证
        IV.
            TimeOut: 指定Cookie的失效时间. 超时后要重新登录.

        从文件名就可以看出是做配置用的,比如配置自定义错误页面,debug,等等
        存放连接字符串是最基本的用法,
        高级一点可以配置httpmodule,httphandler...
        再高级一点可以写一个继承自IConfigurationSectionHandler,添加自定义的配置节...
        功能是很强大的
        ASP.NET提供了一个丰富而可行的配置系统,以帮助管理人员轻松快速的建立自己的WEB应用环境。    ASP.NET提供的是一个层次配置架构,可以帮助WEB应用、站点、机器分别配置自己的扩展配置数据。    ASP.NET的配置系统具有以下优点:
        ●ASP.NET允许配置内容可以和静态内容、动态页面和商业对象放置在同一应用的目录结构下。当管理人员需要安装新的ASP.NET应用时,只需要将应用目录拷贝到新的机器上即可。
        ●ASP.NET的配置内容以纯文本方式保存,可以以任意标准的文本编辑器、XML解析器和脚本语言解释、修改配置内容。
        ●ASP.NET 提供了扩展配置内容的架构,以支持第三方开发者配置自己的内容。
        ●ASP.NET配置文件的更修被系统自动监控,无须管理人员手工干预。


         4.2.2配置文件的规则
        ASP.NET的配置文件是基于XML格式的纯文本文件,存在于应用的各个目录下,统一命名为“config.web”。它决定了所在目录及其子目录的配置信息,并且子目录下的配置信息覆盖其父目录的配置。

        WINNTMicrosoft.NETFramework版本号下的config.web为整个机器的根配置文件,它定义了整个环境下的缺省配置。

        缺省情况下,浏览器是不能够直接访问目录下的config.web文件。

        在运行状态下,ASP.NET会根据远程URL请求,把访问路径下的各个config.web配置文件叠加,产生一个唯一的配置集合。举例来说,一个对URL:http://localhost/webapp/owndir/test.aspx的访问,ASP.NET会根据以下顺序来决定最终的配置情况:
        1..Microsoft.NETFrameworkv.1.00config.web (缺省配置文件)
        2..webappconfig.web (应用的配置)
        3..webappowndirconfig.web (自己的配置)


        4.2.3配置文件的语法规则

       (1)标识
        配置内容被置于config.web文件中的标记<configuration>和</configuration>之间。
        格式:
            <configuration>
                配置内容…
            </configuration>

        (2)配置段句柄说明
        ASP.NET的配置文件架构并未指定任何文件格式或者是支持的配置属性。相反的,它提出了“配置段句柄申明”的概念来支持任意的用户定义配置段。
        格式:
            <configsections>
              <add name=欲定义配置段名 type=处理的句柄函数 />
            </configsections>

        (3)配置段
        具体定义配置的内容,供应用使用。

        以下例子定义了一个“httpmodules”配置段,设置了系统http相关的处理模块
    <configuration>
         <configsections>
           <add name="httpmodules" type="System.Web.Configuration.HttpModules ConfigurationHandler" />
         </configsections>

        <httpmodules>
           <add type="System.Web.SessionState.CookielessSessionModule" />
          <add type="System.Web.Caching.OutputCacheModule" />
          <add type="System.Web.SessionState.SessionStateModule" />
           <add type="System.Web.Security.WindowsAuthenticationModule" />
          <add type="System.Web.Security.CookieAuthenticationModule" />
          <add type="System.Web.Security.PassportAuthenticationModule" />
          <add type="System.Web.Security.CustomAuthenticationModule" />
          <add type="System.Web.Security.UrlAuthorizationModule" />
           <add type="System.Web.Security.FileAuthorizationModule" />
        </httpmodules>
    </configuration>


        4.2. 4   ASP.NET定义的标准配置段

    (1)httpmodule    段: 定义了应用的http请求的处理模块以及诸如安全、日志之类的应用方式
    (2)httphandlers 段: 负责映射URLs到IhttpHandler类
    (3)sessionstat    段: 负责配置http模块的会话状态
    (4)globalization   段:配置应用的公用设置
    (5)compilation    段: 配置ASP.NET的编译环境
    (6)trace      段:配置ASP.NET的跟踪服务
    (7)security         段: ASP.NET的安全配置
    (8)iisprocessmodel 段: 在IIS上配置ASP.NET的处理模式
    (9)browercaps   段: 配置浏览器的兼容部件


        4.2. 5    一个配置读出的例子

    (1)config.web配置文件

        <!--config.web 请放入FormCfg.aspx所在目录-->
          <configuration>
              <!--申明一个test配置段-->
              <configsections>
                  <add name="test" type="System.Web.Configuration.DictionarySectionHandler" />
              </configsections>

              <test>
                  <!--配置一个键key,其内容为just a configure test-->
                  <add key="key" value="just a configure test" />
              </test>
          </configuration>

    (2)读出其内容

        <!--文件名:Application/FormCfg.aspx-->
        <html>
        <head>
        <script language="VB" runat=server>
            sub page_load(s as object ,e as eventargs)
            '取出test配置段的key键的值
            Dim CfgSection As Hashtable = Context.GetConfig("test")
             Dim Msg As String = CStr(CfgSection("key"))

            lblMsg.text=Msg
            end sub
        </script>
        <title>配置信息的读取</title>
        </head>
        <body>
            <center>
                config.web中"test"配置段中key的内容为: <asp:label id=lblmsg runat=server />
            </center>
         </body>
        </html>

    (3)运行结果


        4.2. 6    Config.web配置实例
        <configuration>
            <!--定义用户应用的公用设置,如SQL的sql连接串等等-->
            <appsettings></appsettings>

            <!--设置浏览器的兼容性部件-->
            <browsercaps></browsercaps>

            <!--编译环境设置,非调试模式-->
            <compilation debugmode="false">

                <!--缺省编译语言为vb,以后可以不再在Page中定义脚本语言-->
                <compilers defaultlanguage="vb">

                <!--以MSVSA.dll编译.vb为后缀的VB文件-->
                <compiler language="VB" extension=".vb" type="MSVSA.dll#Microsoft.VB.Compiler"/></compilers>

                <assemblies>
                    <!--加入对System.Data的引用-->
                    <add assembly="System.Data" />

                    <!--去掉对System.Data的引用-->
                    <remove assembly="System.IO" />

                    <!--去掉config.web中包含或继承来的引用-->
                    <clear />
                </assemblies>
            </compilation>

            <!--设置应用全局环境-->
                <!--文件、请求、返回以gb2312编码,以保证浏览器正确显示中文-->
                <globalization fileencoding="gb2312" requestencoding="gb2312" responseencoding="gb2312"/>

                <!--定义用户出错的处理-->
                <!--出错缺省显示defaultredirect指定的页面,mode为on时,遵循customerrors配置段-->
                <!--mode为off时,忽略用户出错,mode为remoteonly时,本地才显示真正的出错原因-->
                <customerrors defaultredirect="AnErrorHasOccured.aspx?ErrNum=-1" mode="remote">

                    <!--当出错码为500时,显示redirect指定的页面-->
                    <error statuscode="500" redirect="AnErrorHasOccured.aspx?ErrNum=500"/>
                </customerrors>

                <!--指定目录webapp的访问权限-->
                <location path="webapp” >
                    <!--非授权用户不能进入webapp目录-->
                    <security>
                    <authorization>
                    <deny users="?" />
                    </authorization>
                    </security>
                 </location>

                <!--定义安全属性-->
                 <security>
                    <authorization>

                    <!--角色为Adminstrators和所有的用户访问其指定的资源-->
                    <allow roles="Adminstrators"/>
                    <allow users="*" />
                     </authorization>
                 </security>
        </configuration>

     <configuration>//顶层元素
    <system.web>//大多应用程序设置位于此元素下
    <sessionState mode='Inproc' timeout='10' />//设置会话状态超时时间
    </system.web>
    </configuration>

    Table 3-1.可用于web.config的顶层配置元素

    元素Element

    含义Purpose

    <authentication>

    指定所使用的客户身份验证模式Specify the client authentication mode to use

    <authorization>

    允许或者拒绝用户或角色的访问Allow or deny users or roles access

    <browserCaps>

    根据用户代理指定浏览器的能力Specify browser capabilities based on user agent

    <clientTarget>

    定义客户目标Define client targets

    <compilation>

    控制同页编译和程序集引用Control page compilation and assembly references

    <customErrors>

    控制错误页显示和定义自定义的错误页Control error page display and define custom error pages

    <globalization>

    设置请求和响应的编码Set the request and response encoding

    <httpHandlers>

    添加或移除HTTP处理程序Add or remove HTTP handlers

    <httpModules>

    添加或移除HTTP模块Add or remove HTTP modules

    <httpRuntime>

    控制HTTP请求的处理Control aspects of HTTP request processing

    <identity>

    为该应用程序指定标识Specify impersonation for this application

    <machineKey>

    控制验证和解密的钥匙Control the validation and decryption key

    <pages>

    设置全局的网页默认属性Set defaults for page attributes globally

    <processModel>

    控制工作者进程的行为方式Control the behavior of the worker process

    <securityPolicy>

    使用相关的策略文件定义信任等级Define trust levels with associated policy files

    <sessionState>

    控制会话状态Control session state

    <trace>

    启用应用程序范围的跟踪Enable application-wide tracing

    <trust>

    选择使用的信任等级Select which trust level to use

    <webServices>

    指定Web服务的协议和范围Specify Web service protocols and extensions

    <appSettings>

    添加应用程序专用的数据元素Add application-specific data elements


    1, 配置的四个层次

    (1)机器:machine.config:位于$FRAMEWORKCONFIG($FRAMEWORK一般是c:winntMicrosoft.NETFrameworkv1.0.3705),
    是.net必须备的默认配置文件。
    web.config用来修改.net默认配置。
    (2)站点:web站点根目录下的web.config,影响全站配置
    (3)程序:应用程序虚目录根下的web.config,影响全虚目录配置
    (3)子目录:虚目录的子目录下的web.config,影响该子目录及其子目录下配置

    Figure 3-1. Hierarchy of Configuration Files

    [图片]

    2,通过location元素简化web.config配置:

    Listing 3-2 Using the location Element

    <configuration>
    <location path="bar">//作用就相当于在bar目录下配置了指定的web.config配置
    <system.web>
    <httpHandlers>
    <remove verb="*" path="*.ashx" />
    </httpHandlers>
    </system.web>
    </location>
    </configuration>


    3,元素的配置规定:
    authentication, sessionState, trust, 和 httpModules(即使在老版本.net允许在子目录中配置,也是不生效的)元素属于应用程序级别的元素,不能配置于子目录下的 web.config。processModel属于机器级别元素,只能用于machine.config。

    4,元素的更改生效时间:
    一般web.config更改后,会自动重新加载程序,并放弃原进程的会话状态和程序状态。如果是processModel更改,只有终止工作者进程(可手工IIS复位,可撤销aspnet_wp.exe进程,也可因进程意外反弹自身)然后重新启动,才能应用新配置,同时放弃所有运行于该机器上的.net 程序状态,缓存数据和会话状态。

    5,IIS与web.config配置
    如果使用了IIS,则IIS的安全配置等优秀于.net配置。如此可以只使用IIS默认配置,而在web.config中具体配置。

    二,常量配置appSettings
    使用appSettings元素的add子元素的key和value属性(键值不分大小写)来存储常量设置。

    Listing 3-3 Specifying Application-Specific Configuration Data

    <!— File: web.config —>
    <configuration>
    <appSettings>
    <add key="DSN"
    value="server=localhost;uid=sa;pwd=;database=pubs"
    />
    <add key="bgColor" value="white" />
    </appSettings>
    </configuration>
    程序启动后,配置就载入内存,有访问权限(.net使用HttpForbiddenHandler来控制对.config.cs, .vb, .asax, .resx文件的访问权限,默认下外部程序不可访问配置文件)的程序就可以使用ConfigurationSettings.AppSettings ["DSN"]的方式直接引用配置的值。

    Listing 3-4 Retrieving appSettings Configuration Data

    <!— File: samplepage.aspx —>
    <%@ Page Language='C#' %>
    <%@ Import Namespace='System.Configuration' %>

    <script runat=server>
    protected void Page_Load(object src, EventArgs e)
    {
    string dsn = ConfigurationSettings.AppSettings["DSN"];
    // use dsn to connect to a database...

    string bgColor =
    ConfigurationSettings.AppSettings["bgColor"];
    // use retrieved background color...
    }
    </script>

    <!— remainder of page not shown —>

    三,进程配置processModel
    只能在machine.config中使用processModel,其改动只在aspnet_wp.exe进程重启后生效,并由unmanaged (非托管?)的aspnet_isapi.dll(ISAPI扩展dll)读取,而非象其他配置一样由managed mechanism(托管机制?)读取。

    Table 3-2. Attributes of the processModel Element

    Attribute

    Values

    Default

    Description

    Enable

    true | false

    true

    指定ASP.NET是驻留在外部工作者进程中(true),还是直接在inetinfo.exe中(false)
    Whether ASP.NET is hosted in an external worker process (true) or directly in inetinfo.exe (false)

    timeout

    Infinite | HH:MM:SS

    Infinite

    进程的总生命期——超时后进程反弹Total life of a process—process bounced after timeout

    idleTimeout

    Infinite | HH:MM:SS

    Infinite

    进程的总空闲期——当到达超时时间时进程反弹Total idle life of a process—process bounced when reached

    shutdownTimeout

    Infinite | HH:MM:SS

    0:00:05

    在撤消进程之前,给予进程关闭的时间Time given to process to shut down before being killed

    requestLimit

    Infinite | number

    Infinite

    进程反弹之前,要服务的总需求量Total number of requests to serve before bouncing process

    requestQueueLimit

    Infinite | number

    5000

    进程反弹之前.所允许的在队列中等待的请求数量
    Number of queued requests allowed before bouncing process

    restartQueueLimit

    Infinite | number

    10

    进程重启时.在队列中等待的请求量Number of requests kept in queue while process is restarting

    memoryLimit

    Number

    60

    进程反弹之前.允许进程使用的物理内存百分数Percentage of physical memory process is allowed to use before bouncing process

    webGarden

    true | false

    false

    指定进程是否与特定CPU建立密切关系(对于多CPU机器)Whether process should be affinitized with a particular CPU (for multi-CPU machines)

    cpuMask

    Bitmask

    0xffffffff

    控制ASP.NET工作者进程所用的CPU数
    (webGarden必须为true)Controls number of CPUs available for ASP.NET worker processes (webGarden must be true)

    userName

    SYSTEM | MACHINE | username

    MACHINE

    运行工作者进程所需的Windows身份
    (MACHINE使用低特权的ASPNET账号)Windows identity to run the worker process in (MACHINE uses low-privileged ASPNET account)

    Password

    AutoGenerate | password

    AutoGenerate

    username的密码Password for username

    logLevel

    All | None | Errors

    Errors

    登记在事件日志中的事件类型Event types logged to event log

    clientConnectedCheck

    HH:MM:SS

    0:00:05

    执行客户连接的检查前.请求保留在队列中的时间Time a request is left in the queue before a client-connected check is performed

    comAuthenticationLevel

    Default | None | Connect | Call | Pkt | PktIntegrity | PktPrivacy

    Connect

    DCOM的安全性身份验证的级别Level of authentication for DCOM security

    comImpersonationLevel

    Default | Anonymous | Identify | Impersonate | Delegate

    Impersonate

    COM的安全性身份验证的级别Authentication level for COM security

    responseRestartDeadlockInterval

    Infinite | HH:MM:SS

    00:09:00

    由于responseRestart-DeadlockInterval而重启工作者进程所需的等待时间Time to wait between restarting worker process because of responseRestartDeadlockInterval

    responseDeadlockInterval

    Infinite | HH:MM:SS

    00:03:00

    在队列中有等待的请求时,为监测死锁而设定的响应超时For deadlock detection, timeout for responses when there are queued requests

    maxWorkerThreads

    Number

    25

    线程池中每个CPU的最多工作者线程量
    Maximum number of I/O threads per CPU in the thread pool

    maxIoThreads

    Number

    25

    线程池中每个CPU的最多I./O线程量Maximum number of I/O threads per CPU in the thread pool

    serverErrorMessageFile

    File name

    ""

    “Server Unavailable"消息的自定义Customization for "Server Unavailable" message


      虽然如上有众多条件能使进程反弹,但默认下只有两个反弹条件:一是程序占用了60%以上的物理内存(该条件由memoryLimit属性来指定),二是有5000多个请求在队列中等待。常用的反弹条件还有明确的超时时间 (timeout),空闲超时时间(累计空闲时间idleTimeout),工作者进程的服务数量上限(requestLimit)。
      可以通过设置webGarden和 cpuMask来设置多cpu的使用方式

    Listing 3-5 Specifying Multiple Worker Processes on a Multi-CPU machine

    <processModel enable="true"
    timeout="Infinite"
    idleTimeout="Infinite"
    shutdownTimeout="0:00:05"
    requestLimit="Infinite"
    requestQueueLimit="5000"
    restartQueueLimit="10"
    memoryLimit="60"
    webGarden="true"//启用该配置后,每个cpu运行一个工作者进程,进程间不能共享会话状态,数据缓存,程序状态
    cpuMask="0x00000007"//相当于二进制0...0111屏蔽,则只使用cpu0,cpu1,cpu2,屏蔽其他cpu
    userName="machine"
    password="AutoGenerate"
    logLevel="Errors"
    clientConnectedCheck="0:00:05"
    comAuthenticationLevel="Connect"
    comImpersonationLevel="Impersonate"
    responseRestartDeadlockInterval="00:09:00"
    responseDeadlockInterval="00:03:00"
    maxWorkerThreads="25"
    maxIoThreads="25" />


      还可以设置maxIoThreads和maxWorkerThreads来控制CPU。(前者一定是I/O(如流或管道)实现端口,后者则是传统非限制流程。由于目前IIS采用异步写已命名管道的方法来处理请求(IIS6直接集成了asp.net,所以不必通过已命名管道而是在工作者线程中直接处理请求),所以.net主要也在I/O中处理请求。)默认的线程设置是25/CPU,一般已经够用。当需要设置超过25直到100线程时,需要谨慎检查是否有异常。

    1, 读取进程信息
    使用ProcessModelInfo(两个获得当前或刚终止工作者进程休息的方法,都调用ProcessInfo类)和ProcessInfo(保存工作者进程的信息)两个静态类来读取进程信息

    Listing 3-6 ProcessModelInfo and ProcessInfo Classes

    public class ProcessModelInfo
    {
    public static ProcessInfo GetCurrentProcessInfo();
    public static ProcessInfo[] GetHistory(int num);
    }

    public class ProcessInfo
    {
    public TimeSpan Age {get;}//年龄
    public int PeakMemoryUsed {get;}//已使用最大内存数
    public int ProcessID {get;}//进程ID
    public int RequestCount {get;}//已服务的请求数
    public ProcessShutdownReason ShutdownReason {get;}//关闭原因
    public DateTime StartTime {get;}//开始时间
    public ProcessStatus Status {get;}//状态
    }

    Figure 3-3. Sample ProcessModelInfo Output

    [图片]


    2 , IIS6.0进程模型的改变(相对IIS5的隔离方式)
      在IIS6.0中,ProcessModel在IIS元数据库中被对等设置代替,现在以XML形式放在metabase.xml文件中,所以忽略了 machine.config中的ProcessModel元素。而且进程不再是ASPNET_wp.exe,而是一个或多个w3wp.exe中,因为已经不限制一个cpu只能一个工作者进程。我们可以配置应用程序池(包含共享相同工作者进程的虚目录集),通过比ProcessModel更多更灵活的设置来控制进程(循环次数/天,分离虚拟内存极限,实际内存极限,cpu使用监视,cpu过载的回收,应用程序池禁用的错误数量极限,启动和关闭时间限制)。
      另外,使用http.sys的内核模式来侦听处理Http请求,而不再是inetinfo.exe。这样就不在进程中而是在系统服务内核中处理Http要求,于是即使用户模式进程出现缺陷甚至崩溃,都不会影响服务内核。

    四,附属设置

    1,assemblies元素
      在web.config中使用@Assembly,可以全局引用GAC部署的应用程序。

    Listing 3-7 Adding an Application-wide Reference to a GAC-Deployed Assembly

    <configuration>
    <!— ... —>
    <system.web>
    <compilation>
    <assemblies>
    <add assembly="Util, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a77a5c561934e089" />
    </assemblies>
    </compilation>
    </system.web>
    </configuration>
    2,pages元素
      在web.config中使用@page指令,可以统一改变应用程序的page默认设置。

    Listing 3-8 Using the pages Element

    <configuration>
    <!— ... —>
    <system.web>
    <pages enableViewState='false' />
    </system.web>
    </configuration>
    五,读取配置信息
      除了通过ConfigurationSettings.AppSettings["xxx"]来访问保存在AppSettings中的值外,通常用 ConfigurationSettings.GetConfig()方法,请求从缓存中读取,如未缓存就请求直接从配置文件读入内存, ConfigurationRecord类使用XmlTextReader类可以直接读取最低层配置的物理xml文件。

    Listing 3-9 Reading Configuration Settings

    object settings =
    ConfigurationSettings.GetConfig("appSettings");
    NameValueCollection nvc = settings as NameValueCollection;
    if (nvc != null)
    {
    string val = (string)nvc["xxx"];
    }

    除了web.config这样的配置的元数据,还有配置的处理程序(解析配置使其获得高扩展性,并在正式读取配置时建立类,同时传送对象的实例建立,开始传送相关配置)。如下图:machine.config中,compilation元素由 CompilationConfigurationHandler类来解析,该类于configSections元素下指定,同时也属于 sectionGroup元素(进一步确定分析范围是 system.web)。另外一个元素appSettings由NameValueFileSectionHandler负责解析,该元素位于配置文件的顶层。

    Figure 3-4. Configuration Section Handlers in machine.config

    [图片]

    每个configSections中的元素都必须实现IConfigurationSectionHandler接口,该接口有一个简单的方法 Create。当配置处理程序的标签被读入时,ConfigurationRecord类(顶层配置文件解析器)调用Create方法。同时,处理程序获得上层配置信息(如果有上层配置的话)和当前HttpConfigurationContext对象(通过输入参数),以及对 XmlNode的引用(最重要信息,由配置处理程序负责解析)。通常处理程序(函数)会遍历XmlNode的每个子节点和属性,返回一个对象,包含所有状态信息。在缓存上述状态信息后,应用程序就可通过ConfigurationSettings.GetConfig()全局引用该状态信息。

    Listing 3-10 IConfigurationSectionHandler Interface

    public interface IConfigurationSectionHandler
    {
    object Create(object parent, object input, XmlNode node);
    }
    asp.net配置部份的处理程序各自都会在内存中建立一个state retainer(状态保持器),如CompilerConfiguration类(compilation元素信息), PagesConfiguration类(pages元素信息 )等。这些配置实例类(都是内部类,不可直接访问,asp.net用它们来设置其创建类中的默认值和其它值)都保存在一个全局的哈希表中,可以用 ConfigurationSettings.GetConfig()来访问该哈希表。

    Figure 3-5. In-memory Configuration Settings Layout

    [图片]



    六,创建自定义的配置处理程序
    除了保存在appSettings元素中之外,还可以自定义配置元素。如下:

    Listing 3-11 Sample Custom Configuration Element

    <!— File: web.config —>
    <configuration>
    <acmeGroup>
    <acme>//指定自定义元素
    <font>Courier New</font>
    <backgroundColor>Green</backgroundColor>
    <underlineLinks>true</underlineLinks>
    <horizontalWidth>600</horizontalWidth>
    <verticalWidth>800</verticalWidth>
    </acme>
    </acmeGroup>
    </configuration>
    首先,我们要建立用于保存配置状态信息的保存机制。
    一种较简单的方法是定义一个类(如AcmeSettings类),用其中的公有数据成员来保存对应的配置元素。

    Listing 3-12 Sample Custom Configuration Settings State Class

    // File: AcmeSettings.cs
    namespace EssentialAspDotNet.Config
    {
    public class AcmeSettings
    {
    public string Font;
    public string BackgroundColor;
    public bool UnderlineLinks;
    public int HorizontalWidth;
    public int VerticalWidth;
    }
    }
    然后,我们要建立一个实现IConfigurationSectionHandler接口的类,用于解析配置文件中自定义部份,并将其状态信息保存到acmeSettings类中。

    Listing 3-13 Sample Custom Configuration Section Handler

    // File: AcmeConfigHandler.cs
    namespace EssentialAspDotNet.Config
    {
    public class AcmeConfigHandler :
    IConfigurationSectionHandler
    {
    public object Create(object parent, object input,
    XmlNode node)
    {
    AcmeSettings aset = new AcmeSettings();

    foreach (XmlNode n in node.ChildNodes)
    {
    switch (n.Name)
    {
    case ("font"):
    aset.Font = n.InnerText;
    break;
    case ("backgroundColor"):
    aset.BackgroundColor = n.InnerText;
    break;
    case ("underlineLinks"):
    aset.UnderlineLinks = bool.Parse(n.InnerText);
    break;
    case ("horizontalWidth"):
    aset.HorizontalWidth = int.Parse(n.InnerText);
    break;
    case ("verticalWidth"):
    aset.VerticalWidth = int.Parse(n.InnerText);
    break;
    }
    }
    return aset;
    }
    }
    }
    最后要通知,我们要用该类解析配置文件中的acme元素。为此,我们在配置文件的configSections中添加一个section元素,用于读取并解析配置文件。(系统范围的machine.config文件,站点范围和应用程序范围的web.config文件都能添加Section元素)

    Listing 3-14 Installing a Custom Configuration Section Handler

    <!— File: web.config —>
    <configuration>
    <configSections>
    <sectionGroup name="acmeGroup">
    <section name="acme"
    type="EssentialAspDotNet.Config.AcmeConfigHandler, AcmeConfigHandler"
    />
    </sectionGroup>
    </configSections>
    <!— ... —>
    </configuration>
    现在,应用程序中的所有网页或者代码块,都能使用ConfigurationSettings.GetConfig()方法访问该配置信息,传递我们创建的部份组(section group)和部份名称(section name),并将结果转变为我们创建的AcmeSettings类。如下:

    Listing 3-15 Accessing Custom Configuration Information

    // File: TestAcmeSettings.aspx
    protected void Page_Load(object src, EventArgs e)
    {
    AcmeSettings set;
    set = ConfigurationSettings.GetConfig("acmeGroup/acme")
    as AcmeSettings;

    // use set here (like set.Font, set.BackgroundColor,
    // etc.)
    }
    还有一种方法,使用NameValueFileSectionHandler,就不需要自即编写实现 IConfigurationSectionHandler接口的类了,而是重用与appSettings元素一样的类。当然也不能用add元素(带有键 /值对)添加新的配置元素,但也能容易地添加新的配置部份。

    Listing 3-16 Adding a Custom Configuration Section with a Prebuilt Handler

    <!— File: web.config —>
    <configuration>
    <configSections>
    <section name="myGroup"
    type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral,
    PublicKeyToken=b77a5c561934e089"/>//添加了名为myGroup的新的配置的部份
    ///其type属性引用了NameValueFileSectionHandler类,该类的实例将其键/值对保存在NameValueCollection中供访问。

    </configSections>

    <myGroup>
    <add key="font" value="Courier New"/>
    <add key="backgroundColor" value="Green"/>
    <add key="underlineLinks" value="true"/>
    <add key="horizontalWidth" value="600"/>
    <add key="verticalWidth" value="800"/>
    </myGroup>
    <!— ... —>
    </configuration>

    Listing 3-17 Accessing Custom Configuration Information with NameValueCollection

    // File: TestAcmeSettings.aspx
    protected void Page_Load(object src, EventArgs e)
    {
    NameValueCollection set;
    set = ConfigurationSettings.GetConfig("myGroup")
    as NameValueCollection;

    // use set here (like set["Font"],
    // set["BackgroundColor"], etc.)
    }
    七,小结:
    ASP.NET使用web.config名字的XML文件取代IIS的元数据库进行配置,machine.config是最顶层的机器配置,而web.config可以放在站点根目录,虚目录根部,子目录等不同层次位置,相应地对其下层发生效用。
    另外还可用新的配置元素,appSettings用于保存数据的通用的名/值对,以供应用程序调用。processModel可以精确控制工作者进程。另外还可通过写一个实现IConfigurationSectionHandler接口的类或者使用系统提供的 NameValueFileSectionHandler类,实现自定义配置。

  • 相关阅读:
    CSS学习笔记(二)选择器
    CSS学习笔记(九)对列表应用样式和创建导航条
    在Eclipse中用远程svn资源库创建项目并提交和更新
    CSS学习笔记(六)圆角框
    CSS学习笔记(五)背景图基础
    SVN创建资源库和远程连接配置
    Struts2标签中支持OGNL表达式的热计算及带参数的<s:a>链接
    php处理字符串格式的计算公式
    CSS学习笔记(十)对表单和数据表格使用样式
    CSS学习笔记(三)层叠和特殊性
  • 原文地址:https://www.cnblogs.com/Alex80/p/5463931.html
Copyright © 2011-2022 走看看