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

    <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类,实现自定义配置。

    原文:http://hi.baidu.com/jiangyangw3r/blog/item/e93e0508ff57cc39e92488ef.html

  • 相关阅读:
    不兼容结构的协调—适配器模式(三)
    Java的时间空间复杂度详解
    Java学习笔记之变量和类变量的访问哲学
    求最大公约数-辗转相除法
    java中怎么遍历HashMap
    Java编程时如何节省内存,效率高
    Java入门需掌握的30个基本概念
    Java各种获取系统当前时间方法和格式
    Java 实现顺序结构线性列表
    Java编程中异常处理的优劣之道
  • 原文地址:https://www.cnblogs.com/zxdz/p/13226584.html
Copyright © 2011-2022 走看看