web.config

 

在开发中经常会遇到这样的情况,在部署程序时为了保密起见并不将源代码随项目一同发布,而我们开发时的环境与部署环境可能不一致(比如数据库不一样),如果在代码中保存这些配置这些信息部署时需要到用户那里更改代码再重新编译,这种部署方式非常麻烦。
在.net 中提供了一种便捷的保存项目配置信息的办法,那就是利用配置文件,配置文件的文件后缀一般是.config,在asp.net中配置文件名一般默认是 web.config。每个web.config文件都是基于XML的文本文件,并且可以保存到Web应用程序中的任何目录中。在发布Web应用程序时 web.config文件并不编译进dll文件中。如果将来客户端发生了变化,仅仅需要用记事本打开web.config文件编辑相关设置就可以重新正常 使用,非常方便。
本篇要讲述的知识如下:
配置文件的查找优先级

配置文件节点说明
配置文件的操作

配置文件的查找优先级
在.net提供了一个针对当前机器的配置文件,这个文件是 machine.config,它位于%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/文件下 (%windir%是系统分区下的系统目录,在命令行模式下输入%windir%然后回车就能查看当前机器的系统目录,在Windows2003及 WindowsXP中%windir%是系统分区下的windows目录,在Windows2000中%windir%是系统分区下的WinNT目录,在 笔者机器上这个系统目录是C:/WINDOWS)。这个文件里面定义了针对当前机器的WinForm程序和asp.net应用程序的配置。下面是 machine.config文件的内容:

 

<? xml version="1.0" encoding="UTF-8" ?>
<!--
    Please refer to machine.config.comments for a description and
    the default values of each configuration section.

    For a full documentation of the schema please refer to
    http://go.microsoft.com/fwlink/?LinkId=42127

    To improve performance, machine.config should contain only those
    settings that differ from their defaults.
-->
< configuration >
     < configSections >
         < section  name ="appSettings"  type ="AppSettingsSection,   requirePermission=/>
        <section name="
connectionStrings" type ="ConnectionStringsSection,  requirePermission=/>
        <section name="
mscorlib" type ="IgnoreSection,  allowLocation=/>
        <section name="
runtime" type ="IgnoreSection,  allowLocation=/>
        <section name="
assemblyBinding" type ="IgnoreSection,  allowLocation=/>
        <section name="
satelliteassemblies" type ="IgnoreSection,  allowLocation=/>
        <section name="
startup" type ="IgnoreSection,  allowLocation=/>
        <section name="
system.codedom" type ="Compiler.CodeDomConfigurationHandler, System, " />
         < section  name ="system.data"  type ="System.Data.Common.DbProviderFactoriesConfigurationHandler,  " />
         < section  name ="system.data.dataset"  type ="NameValueFileSectionHandler, System, "   />
         < section  name ="system.data.odbc"  type ="System.Data.Common.DbProviderConfigurationHandler,  " />
         < section  name ="system.data.oledb"  type ="System.Data.Common.DbProviderConfigurationHandler,  " />
         < section  name ="system.data.oracleclient"  type ="System.Data.Common.DbProviderConfigurationHandler,  " />
         < section  name ="system.data.sqlclient"  type ="System.Data.Common.DbProviderConfigurationHandler,  " />
         < section  name ="system.diagnostics"  type ="System.Diagnostics.SystemDiagnosticsSection, System, " />
         < section  name ="system.runtime.remoting"  type ="IgnoreSection,  allowLocation=/>
        <section name="
system.windows.forms" type ="System.Windows.Forms.WindowsFormsSection, System.Windows.Forms, " />
         < section  name ="windows"  type ="IgnoreSection,  allowLocation=/>
        <sectionGroup name="
system.xml.serialization" type ="Configuration.SerializationSectionGroup, System.Xml, " >
             < section  name ="schemaImporterExtensions"  type ="Configuration.SchemaImporterExtensionsSection, System.Xml, " />
             < section  name ="dateTimeSerialization"  type ="Configuration.DateTimeSerializationSection, System.Xml, " />
             < section  name ="xmlSerializer"  type ="Configuration.XmlSerializerSection, System.Xml, "  requirePermission =/>
        
</sectionGroup >
         < sectionGroup  name ="system.net"  type ="System.Net.Configuration.NetSectionGroup, System, " >
             < section  name ="authenticationModules"  type ="System.Net.Configuration.AuthenticationModulesSection, System, " />
             < section  name ="connectionManagement"  type ="System.Net.Configuration.ConnectionManagementSection, System, " />
             < section  name ="defaultProxy"  type ="System.Net.Configuration.DefaultProxySection, System, " />
             < sectionGroup  name ="mailSettings"  type ="System.Net.Configuration.MailSettingsSectionGroup, System, " >
                 < section  name ="smtp"  type ="System.Net.Configuration.SmtpSection, System, " />
             </ sectionGroup >
             < section  name ="requestCaching"  type ="System.Net.Configuration.RequestCachingSection, System, " />
             < section  name ="settings"  type ="System.Net.Configuration.SettingsSection, System, " />
             < section  name ="webRequestModules"  type ="System.Net.Configuration.WebRequestModulesSection, System, " />
         </ sectionGroup >
         < sectionGroup  name ="system.transactions"  type ="System.Transactions.Configuration.TransactionsSectionGroup, " >
             < section  name ="defaultSettings"  type ="System.Transactions.Configuration.DefaultSettingsSection, " />
             < section  name ="machineSettings"  type ="System.Transactions.Configuration.MachineSettingsSection, "    />
         </ sectionGroup >
         < sectionGroup  name ="system.web"  type ="System.Web.Configuration.SystemWebSectionGroup,  >
            <section name="
anonymousIdentification" type ="System.Web.Configuration.AnonymousIdentificationSection,   " MachineToApplication" />
             < section  name ="authentication"  type ="System.Web.Configuration.AuthenticationSection,   " MachineToApplication" />
             < section  name ="authorization"  type ="System.Web.Configuration.AuthorizationSection,  />
            <section name="
browserCaps" type ="System.Web.Configuration.HttpCapabilitiesSectionHandler,  />
            <section name="
clientTarget" type ="System.Web.Configuration.ClientTargetSection,  />
            <section name="
compilation" type ="System.Web.Configuration.CompilationSection,  />
            <section name="
customErrors" type ="System.Web.Configuration.CustomErrorsSection,  />
            <section name="
deployment" type ="System.Web.Configuration.DeploymentSection,   />
            <section name="
deviceFilters" type ="System.Web.Mobile.DeviceFiltersSection, System.Web.Mobile, />
            <section name="
globalization" type ="System.Web.Configuration.GlobalizationSection,  />
            <section name="
healthMonitoring" type ="System.Web.Configuration.HealthMonitoringSection,   " MachineToApplication" />
             < section  name ="hostingEnvironment"  type ="System.Web.Configuration.HostingEnvironmentSection,   " MachineToApplication" />
             < section  name ="httpCookies"  type ="System.Web.Configuration.HttpCookiesSection,  />
            <section name="
httpHandlers" type ="System.Web.Configuration.HttpHandlersSection,  />
            <section name="
httpModules" type ="System.Web.Configuration.HttpModulesSection,  />
            <section name="
httpRuntime" type ="System.Web.Configuration.HttpRuntimeSection,  />
            <section name="
identity" type ="System.Web.Configuration.IdentitySection,  />
            <section name="
machineKey" type ="System.Web.Configuration.MachineKeySection,   " MachineToApplication" />
             < section  name ="membership"  type ="System.Web.Configuration.MembershipSection,   " MachineToApplication" />
             < section  name ="mobileControls"  type ="System.Web.UI.MobileControls.MobileControlsSection, System.Web.Mobile, />
            <section name="
pages" type ="System.Web.Configuration.PagesSection,  />
            <section name="
processModel" type ="System.Web.Configuration.ProcessModelSection,    allowLocation=/>
            <section name="
profile" type ="System.Web.Configuration.ProfileSection,   " MachineToApplication" />
             < section  name ="roleManager"  type ="System.Web.Configuration.RoleManagerSection,   " MachineToApplication" />
             < section  name ="securityPolicy"  type ="System.Web.Configuration.SecurityPolicySection,   " MachineToApplication" />
             < section  name ="sessionPageState"  type ="System.Web.Configuration.SessionPageStateSection,  />
            <section name="
sessionState" type ="System.Web.Configuration.SessionStateSection,   " MachineToApplication" />
             < section  name ="siteMap"  type ="System.Web.Configuration.SiteMapSection,   " MachineToApplication" />
             < section  name ="trace"  type ="System.Web.Configuration.TraceSection,  />
            <section name="
trust" type ="System.Web.Configuration.TrustSection,   " MachineToApplication" />
             < section  name ="urlMappings"  type ="System.Web.Configuration.UrlMappingsSection,   " MachineToApplication" />
             < section  name ="webControls"  type ="System.Web.Configuration.WebControlsSection,  />
            <section name="
webParts" type ="System.Web.Configuration.WebPartsSection,  />
            <section name="
webServices" type ="System.Web.Services.Configuration.WebServicesSection, System.Web.Services, />
            <section name="
xhtmlConformance" type ="System.Web.Configuration.XhtmlConformanceSection,  />
            <sectionGroup name="
caching" type ="System.Web.Configuration.SystemWebCachingSectionGroup,  >
                <section name="
cache" type ="System.Web.Configuration.CacheSection,   " MachineToApplication" />
                 < section  name ="outputCache"  type ="System.Web.Configuration.OutputCacheSection,   " MachineToApplication" />
                 < section  name ="outputCacheSettings"  type ="System.Web.Configuration.OutputCacheSettingsSection,   " MachineToApplication" />
                 < section  name ="sqlCacheDependency"  type ="System.Web.Configuration.SqlCacheDependencySection,   " MachineToApplication" />
             </ sectionGroup >
             < section  name ="protocols"  type ="System.Web.Configuration.ProtocolsSection,   " MachineToWebRoot" />
         </ sectionGroup >
         < section  name ="system.webServer"  type ="IgnoreSection, />
        <sectionGroup name="
system.runtime.serialization" type ="System.Runtime.Serialization.Configuration.SerializationSectionGroup" >
             < section  name ="dataContractSerializer"  type ="System.Runtime.Serialization.Configuration.DataContractSerializerSection" />
         </ sectionGroup >
         < sectionGroup  name ="system.serviceModel"  type ="System.ServiceModel.Configuration.ServiceModelSectionGroup, System.ServiceModel,  " >
             < section  name ="behaviors"  type ="System.ServiceModel.Configuration.BehaviorsSection, System.ServiceModel,  " />
             < section  name ="bindings"  type ="System.ServiceModel.Configuration.BindingsSection, System.ServiceModel,  " />
             < section  name ="client"  type ="System.ServiceModel.Configuration.ClientSection, System.ServiceModel,  " />
             < section  name ="comContracts"  type ="System.ServiceModel.Configuration.ComContractsSection, System.ServiceModel,  " />
             < section  name ="commonBehaviors"  type ="System.ServiceModel.Configuration.CommonBehaviorsSection, System.ServiceModel,  "    />
             < section  name ="diagnostics"  type ="System.ServiceModel.Configuration.DiagnosticSection, System.ServiceModel,  " />
             < section  name ="extensions"  type ="System.ServiceModel.Configuration.ExtensionsSection, System.ServiceModel " />
             < section  name ="machineSettings"  type ="System.ServiceModel.Configuration.MachineSettingsSection, SMDiagnostic"    />
             < section  name ="serviceHostingEnvironment"  type ="System.ServiceModel.Configuration.ServiceHostingEnvironmentSection" />
             < section  name ="services"  type ="System.ServiceModel.Configuration.ServicesSection, System.ServiceModel " />
         </ sectionGroup >
         < sectionGroup  name ="system.serviceModel.activation"  type ="System.ServiceModel.Activation.Configuration.ServiceModelActivationSectionGroup" >
             < section  name ="diagnostics"  type ="System.ServiceModel.Activation.Configuration.DiagnosticSection, System.ServiceModel,  " />
             < section  name ="net.pipe"  type ="System.ServiceModel.Activation.Configuration.NetPipeSection, System.ServiceModel,  " />
             < section  name ="net.tcp"  type ="System.ServiceModel.Activation.Configuration.NetTcpSection, System.ServiceModel,  " />
         </ sectionGroup >
     </ configSections >
     < configProtectedData  defaultProvider ="RsaProtectedConfigurationProvider" >
         < providers >
             < add  name ="RsaProtectedConfigurationProvider"  type ="RsaProtectedConfigurationProvider, description=" Uses RsaCryptoServiceProvider to encrypt and decrypt" keyContainerName ="NetFrameworkConfigurationKey"  cspProviderName =""  useMachineContainer ="true"  useOAEP =/>
            
<add name ="DataProtectionConfigurationProvider"  type ="DpapiProtectedConfigurationProvider, description=" Uses CryptProtectData and CryptUnProtectData Windows APIs to encrypt and decrypt" useMachineProtection ="true"  keyEntropy ="" />
         </ providers >
     </ configProtectedData >
     < runtime />
     < connectionStrings >
         < add  name ="LocalSqlServer"  connectionString ="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"  providerName ="System.Data.SqlClient" />
     </ connectionStrings >
     < system.data >
         < DbProviderFactories >
             < add  name ="Odbc Data Provider"  invariant ="System.Data.Odbc"  description =".Net Framework Data Provider for Odbc"  type ="System.Data.Odbc.OdbcFactory,  " />
             < add  name ="OleDb Data Provider"  invariant ="System.Data.OleDb"  description =".Net Framework Data Provider for OleDb"  type ="System.Data.OleDb.OleDbFactory,  " />
             < add  name ="OracleClient Data Provider"  invariant ="System.Data.OracleClient"  description =".Net Framework Data Provider for Oracle"  type ="System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, " />
             < add  name ="SqlClient Data Provider"  invariant ="System.Data.SqlClient"  description =".Net Framework Data Provider for SqlServer"  type ="System.Data.SqlClient.SqlClientFactory,  " />
             < add  name ="Microsoft SQL Server Compact Data Provider"  invariant ="System.Data.SqlServerCe.3.5"  description =".NET Framework Data Provider for Microsoft SQL Server Compact"  type ="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe,  45dcd8080cc91" />

        </DbProviderFactories>
    </system.data>
    <system.web>
        <processModel autoConfig="true"/>
        <httpHandlers/>
        <membership>
            <providers>
                <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider,   connectionStringName="LocalSqlServer" enablePasswordRetrieval= enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail= passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
            </providers>
        </membership>
        <profile>
            <providers>
                <add name="AspNetSqlProfileProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Profile.SqlProfileProvider,  />
            </providers>
        </profile>
        <roleManager>
            <providers>
                <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider,  />
                <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider,  />
            </providers>
        </roleManager>
    </system.web>
    <system.serviceModel><commonBehaviors><endpointBehaviors><Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior/></endpointBehaviors><serviceBehaviors><Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior/></serviceBehaviors></commonBehaviors><extensions><behaviorExtensions><add name="Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior" type="Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior, Microsoft.VisualStudio.Diagnostics.ServiceModelSink,  />
                <add name="persistenceProvider" type="System.ServiceModel.Configuration.PersistenceProviderElement, System.WorkflowServices,  "/>
                <add name="workflowRuntime" type="System.ServiceModel.Configuration.WorkflowRuntimeElement, System.WorkflowServices,  "/>
                <add name="enableWebScript" type="System.ServiceModel.Configuration.WebScriptEnablingElement, System.ServiceModel.Web,  "/>
                <add name="webHttp" type="System.ServiceModel.Configuration.WebHttpElement, System.ServiceModel.Web,  "/>
            </behaviorExtensions>
            <bindingElementExtensions>
                <add name="webMessageEncoding" type="System.ServiceModel.Configuration.WebMessageEncodingElement, System.ServiceModel.Web,  "/>
                <add name="context" type="System.ServiceModel.Configuration.ContextBindingElementExtensionElement, System.WorkflowServices,  "/>
            </bindingElementExtensions>
            <bindingExtensions>
                <add name="wsHttpContextBinding" type="System.ServiceModel.Configuration.WSHttpContextBindingCollectionElement, "/>
                <add name="netTcpContextBinding" type="System.ServiceModel.Configuration.NetTcpContextBindingCollectionElement, "/>
                <add name="webHttpBinding" type="System.ServiceModel.Configuration.WebHttpBindingCollectionElement, "/>
                <add name="basicHttpContextBinding" type="System.ServiceModel.Configuration.BasicHttpContextBindingCollectionElement, "/>
            </bindingExtensions>
        </extensions>
        <client>
            <metadata>
                <policyImporters>
                    <extension type="System.ServiceModel.Channels.ContextBindingElementImporter, re=MSIL"/>
                </policyImporters>
                <wsdlImporters>
                    <extension type="System.ServiceModel.Channels.ContextBindingElementImporter, re=MSIL"/>
                </wsdlImporters>
            </metadata>
        </client>
    </system.serviceModel>
</configuration>

 

 

在这个文件夹下还有一个web.config文件,这个文件包含了asp.net网站的常用配置。下面是这个web.config文件的内容: 

 

<?xml version="1.0" encoding="utf-8"?><!-- the root web configuration file -->
<configuration>
  <!--
        Using a location directive with a missing path attribute
        scopes the configuration to the entire machine.  If used in
        conjunction with allowOverride="false", it can be used to
        prevent configuration from being altered on the machine
        Administrators that want to restrict permissions granted to
        web applications should change the default Trust level and ensure
        that overrides are not allowed
    -->
  <location allowOverride="true">
    <system.web>
      <securityPolicy>
        <trustLevel name="Full" policyFile="internal"/>
        <trustLevel name="High" policyFile="web_hightrust.config"/>
        <trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
        <trustLevel name="Low" policyFile="web_lowtrust.config"/>
        <trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
      </securityPolicy>
      <trust level="Full" originUrl=""/>
    </system.web>
  </location>
  <system.net>
    <defaultProxy>
      <proxy usesystemdefault="true"/>
    </defaultProxy>
  </system.net>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
    <browserCaps userAgentCacheKeyLength="64">
      <result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile"/>
    </browserCaps>
    <clientTarget>
      <add alias="ie5" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)"/>
      <add alias="ie4" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)"/>
      <add alias="uplevel" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.1)"/>
      <add alias="downlevel" userAgent="Generic Downlevel"/>
    </clientTarget>
    <compilation>
      <assemblies>
        <add assembly="mscorlib"/>
        <add assembly="System,"/>
        <add assembly="System.Configuration"/>
        <add assembly="System.Web"/>
        <add assembly="System.Data,"/>
        <add assembly="System.Web.Services"/>
        <add assembly="System.Xml,"/>
        <add assembly="System.Drawing"/>
        <add assembly="System.EnterpriseServices"/>
        <add assembly="System.Web.Mobile"/>
        <add assembly="*"/>
        <add assembly="System.Runtime.Serialization, processorArchitecture=MSIL"/>
        <add assembly="System.IdentityModel, processorArchitecture=MSIL"/>
        <add assembly="System.ServiceModel"/>
        <add assembly="System.ServiceModel.Web, "/>
        <add assembly="System.WorkflowServices, "/>
      </assemblies>
      <buildProviders>
        <add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/>
        <add extension=".ascx" type="System.Web.Compilation.UserControlBuildProvider"/>
        <add extension=".master" type="System.Web.Compilation.MasterPageBuildProvider"/>
        <add extension=".asmx" type="System.Web.Compilation.WebServiceBuildProvider"/>
        <add extension=".ashx" type="System.Web.Compilation.WebHandlerBuildProvider"/>
        <add extension=".soap" type="System.Web.Compilation.WebServiceBuildProvider"/>
        <add extension=".resx" type="System.Web.Compilation.ResXBuildProvider"/>
        <add extension=".resources" type="System.Web.Compilation.ResourcesBuildProvider"/>
        <add extension=".wsdl" type="System.Web.Compilation.WsdlBuildProvider"/>
        <add extension=".xsd" type="System.Web.Compilation.XsdBuildProvider"/>
        <add extension=".js" type="System.Web.Compilation.ForceCopyBuildProvider"/>
        <add extension=".lic" type="System.Web.Compilation.IgnoreFileBuildProvider"/>
        <add extension=".licx" type="System.Web.Compilation.IgnoreFileBuildProvider"/>
        <add extension=".exclude" type="System.Web.Compilation.IgnoreFileBuildProvider"/>
        <add extension=".refresh" type="System.Web.Compilation.IgnoreFileBuildProvider"/>
        <add extension=".svc" type="System.ServiceModel.Activation.ServiceBuildProvider, System.ServiceModel"/>
        <add extension=".xoml" type="System.ServiceModel.Activation.WorkflowServiceBuildProvider, System.WorkflowServices, "/>
      </buildProviders>
      <expressionBuilders>
        <add expressionPrefix="Resources" type="System.Web.Compilation.ResourceExpressionBuilder"/>
        <add expressionPrefix="ConnectionStrings" type="System.Web.Compilation.ConnectionStringsExpressionBuilder"/>
        <add expressionPrefix="AppSettings" type="System.Web.Compilation.AppSettingsExpressionBuilder"/>
      </expressionBuilders>
    </compilation>
    <healthMonitoring>
      <bufferModes>
        <add name="Critical Notification" maxBfSz="100" maxFlushSize="20" urgentFlushThreshold="1" rglFlsInv="Infinite" urgentFlushInterval="00:01:00" maxBufferThreads="1"/>
        <add name="Notification" maxBfSz="300" maxFlushSize="20" urgentFlushThreshold="1" rglFlsInv="Infinite" urgentFlushInterval="00:01:00" maxBufferThreads="1"/>
        <add name="Analysis" maxBfSz="1000" maxFlushSize="100" urgentFlushThreshold="100" rglFlsInv="00:05:00" urgentFlushInterval="00:01:00" maxBufferThreads="1"/>
        <add name="Logging" maxBfSz="1000" maxFlushSize="200" urgentFlushThreshold="800" rglFlsInv="00:30:00" urgentFlushInterval="00:05:00" maxBufferThreads="1"/>
      </bufferModes>
      <providers>
        <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider,System.Web,Culture=neutral"/>
        <add connectionStringName="LocalSqlServer" maxEventDetailsLength="1073741823" buffer="false" bufferMode="Notification" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider,System.Web,Culture=neutral"/>
        <add name="WmiWebEventProvider" type="System.Web.Management.WmiWebEventProvider,System.Web,Culture=neutral"/>
      </providers>
      <profiles>
        <add name="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
        <add name="Critical" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" custom=""/>
      </profiles>
      <rules>
        <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
        <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
      </rules>
      <eventMappings>
        <add name="All Events" type="System.Web.Management.WebBaseEvent,System.Web,/>
        <add name="Heartbeats" type="System.Web.Management.WebHeartbeatEvent,System.Web,/>
        <add name="Application Lifetime Events" type="System.Web.Management.WebApplicationLifetimeEvent,System.Web,/>
        <add name="Request Processing Events" type="System.Web.Management.WebRequestEvent,System.Web,/>
        <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent,System.Web,/>
        <add name="Infrastructure Errors" type="System.Web.Management.WebErrorEvent,System.Web,/>
        <add name="Request Processing Errors" type="System.Web.Management.WebRequestErrorEvent,System.Web,/>
        <add name="All Audits" type="System.Web.Management.WebAuditEvent,System.Web,/>
        <add name="Failure Audits" type="System.Web.Management.WebFailureAuditEvent,System.Web,/>
        <add name="Success Audits" type="System.Web.Management.WebSuccessAuditEvent,System.Web,/>
      </eventMappings>
    </healthMonitoring>
    <httpHandlers>
      <add verb="*" path="*.rules" type="System.Web.HttpForbiddenHandler"/>
      <add verb="*" path="*.xoml" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel" validate="false"/>
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler"/>
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler"/>
      <add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory"/>
      <add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory"/>
      <add path="*.asmx" verb="*" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false"/>
      <add path="*.rem" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting," validate="false"/>
      <add path="*.soap" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting," validate="false"/>
      <add path="*.asax" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.ascx" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.master" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.skin" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.browser" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.sitemap" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.dll.config" verb="GET,HEAD" type="System.Web.StaticFileHandler"/>
      <add path="*.exe.config" verb="GET,HEAD" type="System.Web.StaticFileHandler"/>
      <add path="*.config" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.cs" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.csproj" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.vb" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.vbproj" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.webinfo" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.licx" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.resx" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.resources" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.mdb" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.vjsproj" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.java" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.jsl" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.ldb" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.ad" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.dd" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.ldd" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.sd" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.cd" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.adprototype" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.lddprototype" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.sdm" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.sdmDocument" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.mdf" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.ldf" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.exclude" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.refresh" verb="*" type="System.Web.HttpForbiddenHandler"/>
      <add path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel" validate="false"/>
      <add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler"/>
      <add path="*" verb="*" type="System.Web.HttpMethodNotAllowedHandler"/>
    </httpHandlers>
    <httpModules>
      <add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/>
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
      <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/>
      <add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
      <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
      <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
      <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/>
      <add name="Profile" type="System.Web.Profile.ProfileModule"/>
      <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile"/>
      <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel"/>
    </httpModules>
    <mobileControls sessionStateHistorySize="6" cookielessDataDictionaryType="System.Web.Mobile.CookielessData">
      <device name="XhtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlPageAdapter">
        <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlPanelAdapter"/>
        <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlFormAdapter"/>
        <control name="System.Web.UI.MobileControls.TextBox" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlTextBoxAdapter"/>
        <control name="System.Web.UI.MobileControls.Label" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlLabelAdapter"/>
        <control name="System.Web.UI.MobileControls.LiteralText" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlLiteralTextAdapter"/>
        <control name="System.Web.UI.MobileControls.Link" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlLinkAdapter"/>
        <control name="System.Web.UI.MobileControls.Command" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlCommandAdapter"/>
        <control name="System.Web.UI.MobileControls.PhoneCall" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlPhoneCallAdapter"/>
        <control name="System.Web.UI.MobileControls.List" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlListAdapter"/>
        <control name="System.Web.UI.MobileControls.SelectionList" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlSelectionListAdapter"/>
        <control name="System.Web.UI.MobileControls.ObjectList" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlObjectListAdapter"/>
        <control name="System.Web.UI.MobileControls.Image" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlImageAdapter"/>
        <control name="System.Web.UI.MobileControls.ValidationSummary" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlValidationSummaryAdapter"/>
        <control name="System.Web.UI.MobileControls.Calendar" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlCalendarAdapter"/>
        <control name="System.Web.UI.MobileControls.TextView" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlTextViewAdapter"/>
        <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlControlAdapter"/>
        <control name="System.Web.UI.MobileControls.BaseValidator" adapter="System.Web.UI.MobileControls.Adapters.XhtmlAdapters.XhtmlValidatorAdapter"/>
      </device>
      <device name="HtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.HtmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.HtmlPageAdapter">
        <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.HtmlPanelAdapter"/>
        <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.HtmlFormAdapter"/>
        <control name="System.Web.UI.MobileControls.TextBox" adapter="System.Web.UI.MobileControls.Adapters.HtmlTextBoxAdapter"/>
        <control name="System.Web.UI.MobileControls.Label" adapter="System.Web.UI.MobileControls.Adapters.HtmlLabelAdapter"/>
        <control name="System.Web.UI.MobileControls.LiteralText" adapter="System.Web.UI.MobileControls.Adapters.HtmlLiteralTextAdapter"/>
        <control name="System.Web.UI.MobileControls.Link" adapter="System.Web.UI.MobileControls.Adapters.HtmlLinkAdapter"/>
        <control name="System.Web.UI.MobileControls.Command" adapter="System.Web.UI.MobileControls.Adapters.HtmlCommandAdapter"/>
        <control name="System.Web.UI.MobileControls.PhoneCall" adapter="System.Web.UI.MobileControls.Adapters.HtmlPhoneCallAdapter"/>
        <control name="System.Web.UI.MobileControls.List" adapter="System.Web.UI.MobileControls.Adapters.HtmlListAdapter"/>
        <control name="System.Web.UI.MobileControls.SelectionList" adapter="System.Web.UI.MobileControls.Adapters.HtmlSelectionListAdapter"/>
        <control name="System.Web.UI.MobileControls.ObjectList" adapter="System.Web.UI.MobileControls.Adapters.HtmlObjectListAdapter"/>
        <control name="System.Web.UI.MobileControls.Image" adapter="System.Web.UI.MobileControls.Adapters.HtmlImageAdapter"/>
        <control name="System.Web.UI.MobileControls.BaseValidator" adapter="System.Web.UI.MobileControls.Adapters.HtmlValidatorAdapter"/>
        <control name="System.Web.UI.MobileControls.ValidationSummary" adapter="System.Web.UI.MobileControls.Adapters.HtmlValidationSummaryAdapter"/>
        <control name="System.Web.UI.MobileControls.Calendar" adapter="System.Web.UI.MobileControls.Adapters.HtmlCalendarAdapter"/>
        <control name="System.Web.UI.MobileControls.TextView" adapter="System.Web.UI.MobileControls.Adapters.HtmlTextViewAdapter"/>
        <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.HtmlControlAdapter"/>
      </device>
      <device name="UpWmlDeviceAdapters" inheritsFrom="WmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.UpWmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.UpWmlPageAdapter">
      </device>
      <device name="WmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.WmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.WmlPageAdapter">
        <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.WmlPanelAdapter"/>
        <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.WmlFormAdapter"/>
        <control name="System.Web.UI.MobileControls.TextBox" adapter="System.Web.UI.MobileControls.Adapters.WmlTextBoxAdapter"/>
        <control name="System.Web.UI.MobileControls.Label" adapter="System.Web.UI.MobileControls.Adapters.WmlLabelAdapter"/>
        <control name="System.Web.UI.MobileControls.LiteralText" adapter="System.Web.UI.MobileControls.Adapters.WmlLiteralTextAdapter"/>
        <control name="System.Web.UI.MobileControls.Link" adapter="System.Web.UI.MobileControls.Adapters.WmlLinkAdapter"/>
        <control name="System.Web.UI.MobileControls.Command" adapter="System.Web.UI.MobileControls.Adapters.WmlCommandAdapter"/>
        <control name="System.Web.UI.MobileControls.PhoneCall" adapter="System.Web.UI.MobileControls.Adapters.WmlPhoneCallAdapter"/>
        <control name="System.Web.UI.MobileControls.List" adapter="System.Web.UI.MobileControls.Adapters.WmlListAdapter"/>
        <control name="System.Web.UI.MobileControls.SelectionList" adapter="System.Web.UI.MobileControls.Adapters.WmlSelectionListAdapter"/>
        <control name="System.Web.UI.MobileControls.ObjectList" adapter="System.Web.UI.MobileControls.Adapters.WmlObjectListAdapter"/>
        <control name="System.Web.UI.MobileControls.Image" adapter="System.Web.UI.MobileControls.Adapters.WmlImageAdapter"/>
        <control name="System.Web.UI.MobileControls.BaseValidator" adapter="System.Web.UI.MobileControls.Adapters.WmlValidatorAdapter"/>
        <control name="System.Web.UI.MobileControls.ValidationSummary" adapter="System.Web.UI.MobileControls.Adapters.WmlValidationSummaryAdapter"/>
        <control name="System.Web.UI.MobileControls.Calendar" adapter="System.Web.UI.MobileControls.Adapters.WmlCalendarAdapter"/>
        <control name="System.Web.UI.MobileControls.TextView" adapter="System.Web.UI.MobileControls.Adapters.WmlTextViewAdapter"/>
        <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.WmlControlAdapter"/>
      </device>
      <device name="ChtmlDeviceAdapters" inheritsFrom="HtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.ChtmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.ChtmlPageAdapter">
        <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.ChtmlFormAdapter"/>
        <control name="System.Web.UI.MobileControls.Calendar" adapter="System.Web.UI.MobileControls.Adapters.ChtmlCalendarAdapter"/>
        <control name="System.Web.UI.MobileControls.Image" adapter="System.Web.UI.MobileControls.Adapters.ChtmlImageAdapter"/>
        <control name="System.Web.UI.MobileControls.TextBox" adapter="System.Web.UI.MobileControls.Adapters.ChtmlTextBoxAdapter"/>
        <control name="System.Web.UI.MobileControls.SelectionList" adapter="System.Web.UI.MobileControls.Adapters.ChtmlSelectionListAdapter"/>
        <control name="System.Web.UI.MobileControls.Command" adapter="System.Web.UI.MobileControls.Adapters.ChtmlCommandAdapter"/>
        <control name="System.Web.UI.MobileControls.PhoneCall" adapter="System.Web.UI.MobileControls.Adapters.ChtmlPhoneCallAdapter"/>
        <control name="System.Web.UI.MobileControls.Link" adapter="System.Web.UI.MobileControls.Adapters.ChtmlLinkAdapter"/>
      </device>
    </mobileControls>
    <pages>
      <namespaces>
        <add namespace="System"/>
        <add namespace="System.Collections"/>
        <add namespace="System.Collections.Specialized"/>
        <add namespace="System.Configuration"/>
        <add namespace="System.Text"/>
        <add namespace="System.Text.RegularExpressions"/>
        <add namespace="System.Web"/>
        <add namespace="System.Web.Caching"/>
        <add namespace="System.Web.SessionState"/>
        <add namespace="System.Web.Security"/>
        <add namespace="System.Web.Profile"/>
        <add namespace="System.Web.UI"/>
        <add namespace="System.Web.UI.WebControls"/>
        <add namespace="System.Web.UI.WebControls.WebParts"/>
        <add namespace="System.Web.UI.HtmlControls"/>
      </namespaces>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls.WebParts" assembly="System.Web"/>
      </controls>
    </pages>
    <siteMap>
      <providers>
        <add siteMapFile="web.sitemap" name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider, System.Web"/>
      </providers>
    </siteMap>
    <urlMappings enabled="true"/>
    <webControls clientScriptsLocation="/aspnet_client/{0}/{1}/"/>
    <webParts>
      <personalization>
        <providers>
          <add connectionStringName="LocalSqlServer" name="AspNetSqlPersonalizationProvider" type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"/>
        </providers>
        <authorization>
          <deny users="*" verbs="enterSharedScope"/>
          <allow users="*" verbs="modifyState"/>
        </authorization>
      </personalization>
      <transformers>
        <add name="RowToFieldTransformer" type="System.Web.UI.WebControls.WebParts.RowToFieldTransformer"/>
        <add name="RowToParametersTransformer" type="System.Web.UI.WebControls.WebParts.RowToParametersTransformer"/>
      </transformers>
    </webParts>
  </system.web>
</configuration>

 

 

asp.net网站IIS启动的时候会加载配置文件中的配置信息,然后缓存这些信息,这样就不必每次去读取配置信息。在运行过程中asp.net应用程序会监视配置文件的变化情况,一旦编辑了这些配置信息,就会重新读取这些配置信息并缓存。
当我们要读取某个节点或者节点组信息时,是按照如下方式搜索的:
(1)如果在当前页面所在目录下存在web.config文件,查看是否存在所要查找的结点名称,如果存在返回结果并停止查找。
(2)如果当前页面所在目录下不存在web.config文件或者web.config文件中不存在该结点名,则查找它的上级目录,直到网站的根目录。
(3)如果网站根目录下不存在web.config文件或者web.config文件中不存在该节点名则在%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/web.config文件中查找。
(4) 如果在%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/web.config文件中不存在相应 结点,则在%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/machine.config文件 中查找。
(5)如果仍然没有找到则返回null。
所以如果我们对某个网站或者某个文件夹有特定要求的配置,可以在相应的文件夹下创建一个 web.config文件,覆盖掉上级文件夹中的web.config文件中的同名配置即可。这些配置信息的寻找只查找一次,以后便被缓存起来供后来的调 用。在asp.net应用程序运行过程中,如果web.config文件发生更改就会导致相应的应用程序重新启动,这时存储在服务器内存中的用户会话信息 就会丢失(如存储在内存中的Session)。一些软件(如杀毒软件)每次完成对web.config的访问时就会修改web.config的访问时间属 性,也会导致asp.net应用程序的重启。 

 

web.config的所有节点:

 

<?xml version="1.0"?>
<configuration>

  <!-- configSections --> 

  <configSections>  
    <section allowDefinition="MachineToWebRoot"/>
    <section allowExeDefinition="MachineToLocalUser"/>
    <section allowLocation="false" allowOverride="false" restartOnExternalChanges="true" name="" type=""/>
    <sectionGroup name="" type="">
      <section name=""/>
      <sectionGroup></sectionGroup>
    </sectionGroup>
  </configSections>

  <!-- configProtectedData -->

  <configProtectedData>
    <providers>
      <add name="sdf" type="dlfksf"/>
      <clear/>
      <remove name="sdf"/>
    </providers>
  </configProtectedData>

  <!-- appSettings -->  

  <appSettings>
    <add key="" value=""/>
    <clear/>
    <remove key=""/>
  </appSettings>

  <!-- assemblyBinding -->

  <assemblyBinding></assemblyBinding>

  <!-- connectionStrings --> 

  <connectionStrings configSource="" lockItem="false" lockAllElementsExcept="">
    <add connectionString="" name="" providerName=""/>
  </connectionStrings>
  <location allowOverride="false" path=""></location>
  <runtime></runtime>
  <mscorlib></mscorlib>
  <satelliteassemblies></satelliteassemblies>
  <startup></startup>

  <!-- system.codedom --> 

  <system.codedom>
    <compilers>
      <compiler compilerOptions="" extension="" language="" type="" warningLevel=""></compiler>
    </compilers>
  </system.codedom>

  <!-- system.data --> 

  <system.data></system.data>

  <!-- system.data.dataset --> 

  <system.data.dataset></system.data.dataset>

  <!-- system.data.odbc --> 

  <system.data.odbc></system.data.odbc>

  <!-- system.data.oledb --> 

  <system.data.oledb></system.data.oledb>

  <!-- system.data.oracleclient --> 

  <system.data.oracleclient></system.data.oracleclient>

  <!-- system.data.sqlclient --> 

  <system.data.sqlclient></system.data.sqlclient>

  <!-- system.diagnostics --> 

  <system.diagnostics configSource="" lockElements="" lockAllElementsExcept="">
    <assert assertuienabled="false" logfilename=""/>
    <performanceCounters filemappingsize="" lockAllAttributesExcept=""/>
    <sharedListeners lockAllElementsExcept="">
      <add initializeData="" name="" traceOutputOptions="Callstack" type=""></add>
      <add traceOutputOptions="DateTime"></add>
      <add traceOutputOptions="LogicalOperationStack"></add>
      <add traceOutputOptions="None"></add>
      <add traceOutputOptions="ProcessId"></add>
      <add traceOutputOptions="ThreadId"></add>
      <add traceOutputOptions="Timestamp"></add>
      <remove name=""></remove>
    </sharedListeners>
    <sources lockItem="true"></sources>
    <switches lockAllAttributesExcept=""></switches>
    <trace autoflush="true" indentsize="" useGlobalLock="true" lockAttributes=""></trace>
  </system.diagnostics>

  <!-- system.net --> 

  <system.net>
    <authenticationModules configSource="" lockAllElementsExcept="">
      <add type=""/>
    </authenticationModules>
    <connectionManagement configSource="" lockAttributes="">
      <clear/>
    </connectionManagement>
    <defaultProxy configSource="" enabled="false" useDefaultCredentials="true">
      <bypasslist lockAllAttributesExcept="">
        <add address="" lockAllAttributesExcept=""/>
      </bypasslist>
      <module type=""/>
      <proxy autoDetect="False" bypassonlocal="True" proxyaddress=""/>
      <proxy scriptLocation="" usesystemdefault="Unspecified"/>
    </defaultProxy>
    <mailSettings>
      <smtp configSource="" deliveryMethod="Network">
        <network defaultCredentials="false" host="" password="" port="" userName=""/>
        <specifiedPickupDirectory pickupDirectoryLocation="sdlfkj"/>
      </smtp>
    </mailSettings>
    <requestCaching configSource="" defaultPolicyLevel="BypassCache">
      <defaultFtpCachePolicy policyLevel="Revalidate"/>
      <defaultHttpCachePolicy maximumAge=""/>
    </requestCaching>
    <requestCaching defaultPolicyLevel="CacheIfAvailable">
      <defaultFtpCachePolicy policyLevel="CacheIfAvailable"/>
    </requestCaching>
    <requestCaching defaultPolicyLevel="CacheOnly"></requestCaching>
    <requestCaching defaultPolicyLevel="NoCacheNoStore"></requestCaching>
    <requestCaching defaultPolicyLevel="Default"></requestCaching>
    <requestCaching defaultPolicyLevel="Reload">
      <defaultFtpCachePolicy policyLevel="CacheOnly"/>
      <defaultHttpCachePolicy maximumAge="" maximumStale="" minimumFresh="" policyLevel="Refresh"/>
    </requestCaching>
    <requestCaching defaultPolicyLevel="Revalidate"></requestCaching>
    <settings configSource="" lockAttributes="">
      <httpWebRequest maximumErrorResponseLength="" maximumResponseHeadersLength="" maximumUnauthorizedUploadLength="" useUnsafeHeaderParsing="false"/>
      <ipv6 enabled="true" lockItem="false"/>
      <performanceCounters enabled="false"/>
      <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false"/>
      <servicePointManager dnsRefreshTimeout="" enableDnsRoundRobin=""/>
      <servicePointManager expect100Continue="" useNagleAlgorithm=""/>
      <socket alwaysUseCompletionPortsForAccept="" alwaysUseCompletionPortsForConnect=""/>
      <webProxyScript downloadTimeout=""/>
    </settings>
    <webRequestModules configSource="">
      <add prefix="" type=""/>
      <clear/>
      <remove prefix=""/>
    </webRequestModules>
  </system.net>

  <!-- system.runtime.remoting --> 

  <system.runtime.remoting></system.runtime.remoting>

  <!-- system.transactions --> 

  <system.transactions>
    <defaultSettings configSource="" distributedTransactionManagerName="" timeout=""/>
    <machineSettings configSource="" maxTimeout=""/>
  </system.transactions>

  <!-- system.web --> 

  <system.web>
    < anonymousIdentification configSource="" cookieless="AutoDetect"/>
    <anonymousIdentification cookieName="" cookieless="UseCookies"/>
    <anonymousIdentification cookiePath="" cookieless="UseDeviceProfile"/>
    <anonymousIdentification cookieProtection="All" cookieless="UseUri"/>
    <anonymousIdentification cookieProtection="Encryption" cookieRequireSSL="false"/>
    <anonymousIdentification cookieProtection="None" cookieSlidingExpiration="true"/>
    <anonymousIdentification cookieProtection="Validation" cookieTimeout=""/>
    <anonymousIdentification domain="" enabled="true"/>
    <authentication configSource="" mode="Forms">
      <forms cookieless="AutoDetect" defaultUrl="" domain="">
        <credentials passwordFormat="Clear">
          <user name="" password=""/>
        </credentials>
        <credentials passwordFormat="MD5"></credentials>
        <credentials passwordFormat="SHA1"></credentials>
      </forms>
      <forms enableCrossAppRedirects="false" loginUrl="" name=""></forms>
      <forms path="" protection="Encryption" requireSSL="false"></forms>
      <forms slidingExpiration="false" timeout=""></forms>
      <passport redirectUrl=""/>
    </authentication>
    <authorization configSource="" lockItem="false">
      <allow roles="" users="" verbs="" lockElements=""/>
      <deny roles="" users="" verbs="" lockAttributes=""/>
    </authorization>
    <browserCaps></browserCaps>
    <caching>
      <cache configSource="" disableExpiration="false" disableMemoryCollection="true"/>
      <cache percentagePhysicalMemoryUsedLimit="" privateBytesLimit="" privateBytesPollTime=""/>
      <outputCache configSource="" enableFragmentCache="false" enableOutputCache="false"/>
      <outputCache omitVaryStar="false" sendCacheControlHeader="true"/>
      <outputCacheSettings configSource="" lockAllElementsExcept="">
        <outputCacheProfiles lockAllElementsExcept="">
          <add duration="" enabled="false" location="Any" name="" noStore="false"/>
          <add location="Client" sqlDependency="" varyByControl=""/>
          <add location="Downstream" varyByCustom="" varyByHeader=""/>
          <add location="None" varyByParam=""/>
          <add location="Server"/>
          <add location="ServerAndClient"/>
          <clear/>
          <remove name=""/>
        </outputCacheProfiles>
      </outputCacheSettings>
      <sqlCacheDependency configSource="" enabled="false" pollTime="" lockItem="false">
        <databases lockAttributes="">
          <add connectionStringName="" name="" pollTime=""/>
          <clear/>
          <remove name=""/>
        </databases>
      </sqlCacheDependency>
    </caching>
    <clientTarget configSource="" lockAllAttributesExcept="">
      <add alias="" userAgent=""/>
      <clear/>
      <remove alias=""/>
    </clientTarget>
    <compilation assemblyPostProcessorType="" batch="false" batchTimeout="">
      <assemblies lockAllAttributesExcept="">
        <add assembly="" lockAllAttributesExcept=""/>
        <clear/>
        <remove assembly=""/>
      </assemblies>
      <buildProviders lockAllElementsExcept="">
        <add extension="" type=""/>
        <clear/>
        <remove extension=""/>
      </buildProviders>
      <codeSubDirectories lockElements="">
        <add directoryName=""/>
      </codeSubDirectories>
      <expressionBuilders lockAttributes="">
        <add expressionPrefix="" type=""/>
      </expressionBuilders>
    </compilation>
    <compilation configSource="" debug="false" defaultLanguage="" explicit="false"></compilation>
    <compilation maxBatchGeneratedFileSize="" maxBatchSize="" numRecompilesBeforeAppRestart=""></compilation>
    <compilation strict="false" tempDirectory="" urlLinePragmas="false"></compilation>
    <customErrors configSource="" defaultRedirect="" mode="Off">
      <error redirect="" statusCode=""/>
    </customErrors>
    <customErrors mode="On"></customErrors>
    <customErrors mode="RemoteOnly"></customErrors>
    <deployment configSource="" retail="true"/>
    <deviceFilters configSource="">
      <filter argument="" compare="" method="" name="" type=""/>
    </deviceFilters>
    <globalization configSource="" culture="" enableBestFitResponseEncoding="false"/>
    <globalization enableClientBasedCulture="false" fileEncoding="" requestEncoding=""/>
    <globalization responseEncoding="" resourceProviderFactoryType="" uiCulture=""/>
    <healthMonitoring configSource="" enabled="false" heartbeatInterval="">
      <bufferModes lockAllAttributesExcept="">
        <add maxBufferSize="Infinite" maxBufferThreads="Infinite" maxFlushSize="Infinite"/>
        <add name="" regularFlushInterval="" urgentFlushInterval="" urgentFlushThreshold="Infinite"/>
        <clear/>
        <remove name=""/>
      </bufferModes>
      <eventMappings lockAttributes="">
        <add endEventCode="" name="" startEventCode="" type=""/>
        <clear/>
        <remove name=""/>
      </eventMappings>
      <profiles lockAttributes="">
        <add custom="" maxLimit="Infinite" minInstances="" minInterval="" name=""/>
        <clear/>
        <remove name=""/>
      </profiles>
      <providers lockItem="true">
        <add name="" type=""/>
        <remove name=""/>
        <clear/>
      </providers>
      <rules lockAttributes="">
        <add custom="" eventName="" maxLimit="Infinite" minInstances="" minInterval=""/>
        <add name="" profile="" provider=""/>
        <clear/>
        <remove/>
      </rules>
    </healthMonitoring>
    <hostingEnvironment configSource="" idleTimeout="" shadowCopyBinAssemblies="false" shutdownTimeout=""/>
    <httpCookies configSource="" domain="" httpOnlyCookies="false" requireSSL="false"/>
    <httpHandlers configSource="">
      <add path="" type="" validate="false" verb=""/>
      <clear/>
      <remove path="" verb=""/>
    </httpHandlers>
    <httpModules configSource="">
      <add name="" type=""/>
      <clear/>
      <remove name=""/>
    </httpModules>
    <httpRuntime apartmentThreading="false" appRequestQueueLimit="" configSource=""/>
    <httpRuntime delayNotificationTimeout="" enable="false" enableHeaderChecking="false"/>
    <httpRuntime enableKernelOutputCache="false" enableVersionHeader="false" executionTimeout=""/>
    <httpRuntime maxRequestLength="" maxWaitChangeNotification="" minFreeThreads="" minLocalRequestFreeThreads=""/>
    <httpRuntime requestLengthDiskThreshold="" requireRootedSaveAsPath="true"/>
    <httpRuntime sendCacheControlHeader="false" shutdownTimeout=""/>
    <httpRuntime useFullyQualifiedRedirectUrl="false" waitChangeNotification=""/>
    <identity configSource="" impersonate="false" password="" userName=""/>
    <machineKey configSource="" decryption="" decryptionKey="" validation="AES" validationKey=""/>
    <machineKey validation="MD5"/>
    <machineKey validation="SHA1"/>
    <machineKey validation="3DES"/>
    <membership configSource="" defaultProvider="" hashAlgorithmType=""  userIsOnlineTimeWindow="">
      <providers lockAllAttributesExcept="">
        <add name="" type=""/>
      </providers>
    </membership>
    <mobileControls allowCustomAttributes="false" configSource="" cookielessDataDictionaryType="" sessionStateHistorySize="">
      <clear/>
      <device inheritsFrom="" name="" pageAdapter="" predicateClass="" predicateMethod="">
        <clear/>
        <control adapter="" name=""/>
        <remove name=""/>
      </device>
      <remove name=""></remove>
    </mobileControls>
    <pages asyncTimeout="" autoEventWireup="false" buffer="false" compilationMode="Always" configSource=""></pages>
    <pages compilationMode="Auto" enableEventValidation="false" enableSessionState="ReadOnly" enableViewState="false" enableViewStateMac="true"></pages>
    <pages maintainScrollPositionOnPostBack="false" masterPageFile="" maxPageStateFieldLength=""></pages>
    <pages pageBaseType="" pageParserFilterType="" smartNavigation="false" styleSheetTheme=""></pages>
    <pages theme="" userControlBaseType="" validateRequest="false" viewStateEncryptionMode="Always">
      <controls lockAllElementsExcept="">
        <add assembly="" namespace="" src="" tagName="" tagPrefix=""/>
      </controls>
      <namespaces autoImportVBNamespace="false">
        <add namespace=""/>
        <remove namespace=""/>
        <clear/>
      </namespaces>
      <tagMapping lockAttributes="">
        <add mappedTagType="" tagType=""/>
        <clear/>
        <remove tagType=""/>
      </tagMapping>
    </pages>
    <processModel autoConfig="false" clientConnectedCheck="" comAuthenticationLevel="Call"/>
    <processModel comAuthenticationLevel="Connect" comImpersonationLevel="Anonymous"/>
    <processModel comAuthenticationLevel="Default" comImpersonationLevel="Default"/>
    <processModel comAuthenticationLevel="None" comImpersonationLevel="Delegate"/>
    <processModel comAuthenticationLevel="Pkt" comImpersonationLevel="Identify"/>
    <processModel comAuthenticationLevel="PktIntegrity" comImpersonationLevel="Impersonate"/>
    <processModel comAuthenticationLevel="PktPrivacy" configSource="" cpuMask=""/>
    <processModel enable="false" idleTimeout="" maxAppDomains="" maxIoThreads=""/>
    <processModel maxWorkerThreads="" memoryLimit="" minIoThreads="" minWorkerThreads=""/>
    <processModel password="" pingFrequency="" pingTimeout=""/>
    <processModel requestLimit="Infinite" requestQueueLimit="Infinite" responseDeadlockInterval="" responseRestartDeadlockInterval="" restartQueueLimit="Infinite"/>
    <processModel serverErrorMessageFile="" shutdownTimeout="" timeout="" userName="" webGarden="true"/>
    <profile automaticSaveEnabled="false" configSource="" defaultProvider="" enabled="false" inherits="">
      <properties lockAllAttributesExcept="">
        <add allowAnonymous="false" customProviderData="" defaultValue=""/>
        <add name="" provider="" readOnly="false" serializeAs="Binary" type=""/>
        <add serializeAs="ProviderSpecific"/>
        <add serializeAs="String"/>
        <add serializeAs="Xml"/>
        <clear/>
        <group name="">
          <add allowAnonymous="false" customProviderData="" serializeAs="Binary"/>
          <clear/>
          <remove name=""/>
        </group>
        <remove name=""/>
      </properties>
      <providers lockAllElementsExcept="">
        <add name="" type=""/>
      </providers>
    </profile>
    <roleManager cacheRolesInCookie="false" configSource="" cookieName=""></roleManager>
    <roleManager cookiePath="" cookieProtection="Encryption" cookieRequireSSL="false"></roleManager>
    <roleManager cookieSlidingExpiration="false" cookieTimeout="" createPersistentCookie="false"></roleManager>
    <roleManager defaultProvider="" domain="" enabled="false" maxCachedResults="">
      <providers lockAllElementsExcept="">
        <add name="" type=""/>
      </providers>
    </roleManager>
    <securityPolicy configSource="">
      <trustLevel name="" policyFile=""/>
    </securityPolicy>
    <sessionPageState configSource="" historySize=""/>
    <sessionState allowCustomSqlDatabase="false" configSource="" cookieless="UseCookies" cookieName=""></sessionState>
    <sessionState customProvider="" mode="SQLServer" partitionResolverType="" regenerateExpiredSessionId="false"></sessionState>
    <sessionState sessionIDManagerType="" sqlCommandTimeout="" sqlConnectionString="" stateConnectionString="" stateNetworkTimeout=""></sessionState>
    <sessionState timeout="" useHostingIdentity="false">
      <providers lockAttributes="">
        <add name="" type=""/>
      </providers>
    </sessionState>
    <siteMap configSource="" defaultProvider="" enabled="false" lockItem="false">
      <providers lockElements="">
        <add name="" type=""/>
      </providers>
    </siteMap>
    <trace configSource="" enabled="true" localOnly="false" lockAllAttributesExcept="" lockAllElementsExcept="" lockAttributes="" lockElements="" lockItem="false"/>
    <trace mostRecent="true" pageOutput="false" requestLimit="" traceMode="SortByCategory" writeToDiagnosticsTrace="false"/>
    <trust configSource="" level="" originUrl="" processRequestInApplicationTrust="false"/>
    <urlMappings configSource="" enabled="false">
      <add mappedUrl="" url=""/>
      <remove url=""/>
    </urlMappings>
    <webControls clientScriptsLocation="" configSource="" lockItem="false"/>
    <webParts configSource="" enableExport="false">
      <personalization defaultProvider="" lockItem="false">
        <authorization lockItem="false">
          <allow roles="" users="" verbs=""/>
          <deny roles="" users="" verbs=""/>
        </authorization>
        <providers>
          <add name="" type=""/>
        </providers>
      </personalization>
      <transformers>
        <add/>
        <remove name=""/>
      </transformers>
    </webParts>
    <webServices configSource="">
      <conformanceWarnings>
        <add name="BasicProfile1_1"/>
      </conformanceWarnings>
      <diagnostics suppressReturningExceptions="false"/>
      <protocols>
        <add name="AnyHttpSoap"/>
        <add name="Documentation"/>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
        <add name="HttpPostLocalhost"/>
        <add name="HttpSoap"/>
        <add name="HttpSoap12"/>
      </protocols>
      <serviceDescriptionFormatExtensionTypes>
        <add type=""/>
      </serviceDescriptionFormatExtensionTypes>
      <soapEnvelopeProcessing readTimeout="Infinite" strict="false"/>
      <soapExtensionImporterTypes>
        <add type=""/>
      </soapExtensionImporterTypes>
      <soapExtensionReflectorTypes>
        <add type=""/>
      </soapExtensionReflectorTypes>
      <soapExtensionTypes>
        <add type="" priority="" group="High"/>
      </soapExtensionTypes>
      <soapServerProtocolFactory type=""/>
      <soapTransportImporterTypes>
        <add type=""/>
      </soapTransportImporterTypes>
      <wsdlHelpGenerator href=""/>
    </webServices>
    <xhtmlConformance mode="Legacy" configSource=""/>
    <xhtmlConformance mode="Strict"/>
    <xhtmlConformance mode="Transitional"/>
  </system.web>

  <!-- system.webServer --> 

  <system.webServer></system.webServer>

  <!-- system.windows.forms --> 

  <system.windows.forms configSource="" jitDebugging="false"/>

  <!-- system.xml.serialization --> 

  <system.xml.serialization>
    <dateTimeSerialization configSource="" mode="Default"/>
    <dateTimeSerialization mode="Local"/>
    <dateTimeSerialization mode="Roundtrip"/>
    <schemaImporterExtensions configSource="">
      <add name="" type=""/>
    </schemaImporterExtensions>
    <xmlSerializer checkDeserializeAdvances="false" configSource=""/>
  </system.xml.serialization>

  <!-- windows --> 

  <windows></windows>
</configuration>

 

 

web.confg的示例文件:

<? xml version="1.0" ?>
< configuration  xmlns ="http://schemas.microsoft.com/.NetConfiguration/v2.0" >
     < connectionStrings >
         < add  name ="SQLProfileConnString"  connectionString ="server=RLJXYWJOGE98QVF;database=MSPetShop4Profile;user id=mspetshop;password=pass@word1;min pool size=4;max pool size=4;"  providerName ="System.Data.SqlClient" />
         < add  name ="SQLMembershipConnString"  connectionString ="server=RLJXYWJOGE98QVF;database=MSPetShop4Services;user id=mspetshop;password=pass@word1;min pool size=4;max pool size=4;"  providerName ="System.Data.SqlClient" />
         < add  name ="SQLConnString1"  connectionString ="server=RLJXYWJOGE98QVF;database=MSPetShop4;user id=mspetshop;password=pass@word1;min pool size=4;max pool size=4;"  providerName ="System.Data.SqlClient" />
         < add  name ="SQLConnString2"  connectionString ="server=RLJXYWJOGE98QVF;database=MSPetShop4;user id=mspetshop;password=pass@word1;max pool size=4;min pool size=4;"  providerName ="System.Data.SqlClient" />
         < add  name ="SQLConnString3"  connectionString ="server=RLJXYWJOGE98QVF;database=MSPetShop4Orders;user id=mspetshop;password=pass@word1;min pool size=4;max pool size=4;"  providerName ="System.Data.SqlClient" />
         < add  name ="OraProfileConnString"  connectionString =""  providerName ="System.Data.OracleClient" />
         < add  name ="OraMembershipConnString"  connectionString =""  providerName ="System.Data.OracleClient" />
         < add  name ="OraConnString1"  connectionString =""  providerName ="System.Data.OracleClient" />
         < add  name ="OraConnString2"  connectionString =""  providerName ="System.Data.OracleClient" />
         < add  name ="OraConnString3"  connectionString =""  providerName ="System.Data.OracleClient" />
     </ connectionStrings >
     < appSettings >
         <!--  Pet Shop DAL configuration settings. Possible values: PetShop.SQLServerDAL for SqlServer, PetShop.OracleServerDALfor Oracle.  -->
         < add  key ="WebDAL"  value ="PetShop.SQLServerDAL" />
         < add  key ="OrdersDAL"  value ="PetShop.SQLServerDAL" />
         < add  key ="ProfileDAL"  value ="PetShop.SQLProfileDAL" />
         <!--  Enable data caching  -->
         < add  key ="EnableCaching"  value ="true" />
         <!--  Cache duration (in hours-whole number only)  -->
         < add  key ="CategoryCacheDuration"  value ="12" />
         < add  key ="ProductCacheDuration"  value ="12" />
         < add  key ="ItemCacheDuration"  value ="12" />
         <!--  Cache dependency options. Possible values: PetShop.TableCacheDependency for SQL Server and keep empty for ORACLE  -->
         < add  key ="CacheDependencyAssembly"  value ="PetShop.TableCacheDependency" />
         <!--  CacheDatabaseName should match the name under caching section, when using TableCacheDependency  -->
         < add  key ="CacheDatabaseName"  value ="MSPetShop4" />
         <!--  *TableDependency lists table dependency for each instance separated by comma  -->
         < add  key ="CategoryTableDependency"  value ="Category" />
         < add  key ="ProductTableDependency"  value ="Product,Category" />
         < add  key ="ItemTableDependency"  value ="Product,Category,Item" />
         <!--  Order processing options (Asynch/Synch)  -->
         < add  key ="OrderStrategyAssembly"  value ="PetShop.BLL" />
         < add  key ="OrderStrategyClass"  value ="PetShop.BLL.OrderSynchronous" />
         <!--  Asynchronous Order options  -->
         < add  key ="OrderMessaging"  value ="PetShop.MSMQMessaging" />
         < add  key ="OrderQueuePath"  value ="FormatName:DIRECT=OS:MachineName\Private$\PSOrders" />
         <!--  Application Error Log  -->
         < add  key ="Event Log Source"  value =".NET Pet Shop 4.0" />
     </ appSettings >
     < system.web >
         < pages  theme ="PetShop"  styleSheetTheme ="PetShop" />
         <!--  
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        
-->
         < compilation  debug ="false" >
         </ compilation >
         <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
         
-->
         < authentication  mode ="Forms" >
             < forms  name ="PetShopAuth"  loginUrl ="SignIn.aspx"  protection ="None"  timeout ="60" />
         </ authentication >
         <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.
        
-->
         < customErrors  defaultRedirect ="Error.aspx"  mode ="RemoteOnly" />
         < sessionState  mode ="Off" />
         < anonymousIdentification  enabled ="true" />
         < profile  automaticSaveEnabled ="false"  defaultProvider ="ShoppingCartProvider" >
             < providers >
                 < add  name ="ShoppingCartProvider"  connectionStringName ="SQLProfileConnString"  type ="PetShop.Profile.PetShopProfileProvider"  applicationName =".NET Pet Shop 4.0" />
                 < add  name ="WishListProvider"  connectionStringName ="SQLProfileConnString"  type ="PetShop.Profile.PetShopProfileProvider"  applicationName =".NET Pet Shop 4.0" />
                 < add  name ="AccountInfoProvider"  connectionStringName ="SQLProfileConnString"  type ="PetShop.Profile.PetShopProfileProvider"  applicationName =".NET Pet Shop 4.0" />
             </ providers >
             < properties >
                 < add  name ="ShoppingCart"  type ="PetShop.BLL.Cart"  allowAnonymous ="true"  provider ="ShoppingCartProvider" />
                 < add  name ="WishList"  type ="PetShop.BLL.Cart"  allowAnonymous ="true"  provider ="WishListProvider" />
                 < add  name ="AccountInfo"  type ="PetShop.Model.AddressInfo"  allowAnonymous ="false"  provider ="AccountInfoProvider" />
             </ properties >
         </ profile >
         <!--  Membership Provider for SqlServer  -->
         < membership  defaultProvider ="SQLMembershipProvider" >
             < providers >
                 < add  name ="SQLMembershipProvider"  type ="System.Web.Security.SqlMembershipProvider"  connectionStringName ="SQLMembershipConnString"  applicationName =".NET Pet Shop 4.0"  enablePasswordRetrieval ="false"  enablePasswordReset ="true"  requiresQuestionAndAnswer ="false"  requiresUniqueEmail ="false"  passwordFormat ="Hashed" />
             </ providers >
         </ membership >
         <!--  Membership Provider for Oracle  -->
         <!--  
        <membership defaultProvider="OracleMembershipProvider">
            <providers>
                <clear/>
                <add name="OracleMembershipProvider" 
                    type="PetShop.Membership.OracleMembershipProvider" 
                    connectionStringName="OraMembershipConnString" 
                    enablePasswordRetrieval="false" 
                    enablePasswordReset="false" 
                    requiresUniqueEmail="false" 
                    requiresQuestionAndAnswer="false" 
                    minRequiredPasswordLength="7" 
                    minRequiredNonalphanumericCharacters="1" 
                    applicationName=".NET Pet Shop 4.0" 
                    hashAlgorithmType="SHA1" 
                    passwordFormat="Hashed"/>
            </providers>
        </membership>
         
-->
         < caching >
             < sqlCacheDependency  enabled ="true"  pollTime ="10000" >
                 < databases >
                     < add  name ="MSPetShop4"  connectionStringName ="SQLConnString1"  pollTime ="10000" />
                 </ databases >
             </ sqlCacheDependency >
         </ caching >
     </ system.web >
     < location  path ="UserProfile.aspx" >
         < system.web >
             < authorization >
                 < deny  users ="?" />
             </ authorization >
         </ system.web >
     </ location >
     < location  path ="CheckOut.aspx" >
         < system.web >
             < authorization >
                 < deny  users ="?" />
             </ authorization >
         </ system.web >
     </ location >

</configuration> 

 

 

资料参考:

 

Web.config File - ASP.NET

简介

The time you start developing your web application until you finish the application, you will more often use theWeb.config file not only for securing your application but also for wide range of other purposes which it is intended for. ASP.NET Web.config file provides you a flexible way to handle all your requirements at the application level. Despite the simplicity provided by the .NET Framework to work with web.config, working with configuration files would definitely be a task until you understand it clearly. This could be one of the main reasons that I started writing this article.

This article would be a quick reference for the professional developers and for those who just started programming in .NET. This article would help them to understand the ASP.NET configuration in an efficient way. The readers may skip the reading section "Authentication, Authorization, Membership Provider, Role Provider and Profile Provider Settings", as most of them are familiar with those particular settings.

背景

In this article, I am going to explain about the complete sections and settings available in the Web.config file and how you can configure them to use in the application. In the later section of the article, we will see the .NET classes that are used to work with the configuration files. 本文包括以下几方面内容:

  1. Web.config sections/settings
  2. Reading Web.config
  3. Writing or manipulating Web.config
  4. Encrypting the Web.config and
  5. Creating your own Custom Configuration Sections

需要记住的几点内容

ASP.NET Web.config allows you to define or revise the configuration settings at the time of developing the application or at the time of deployment or even after deployment. 要理解Web.config,需要记住以下几点:

  • Web.config文件以XML格式存储,让使用更方便。
  • 一个应用程序中可以有任意多个Web.config文件。每个Web.config将配置应用于它所在目录及该目录包含的所有子目录。
  • 所有的Web.config文件继承于Web.config根文件。根Web.config文件位于 systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config
  • IIS不允许通过浏览器访问Web.config文件。
  • 修改Web.config 不需要重启web服务器。

Web.config Settings

Before we start working with configuration settings of ASP.NET, 我们看一下Web.config文件的层次结构:

<configuration>

 

        <configSections>

            <sectionGroup>

            </sectionGroup>

        </configSections>

 

        <system.web>

        </system.web>

 

        <connectionStrings>

        </connectionStrings>

 

        <appSettings>

        </appSettings>

        …………………………………………………………………………………………………………

        …………………………………………………………………………………………………………

        …………………………………………………………………………………………………………

 

</configuration>

从上面的树结构可知,标签configurationWeb.config文件的根元素。根元素下是所有其他的子元素。Each element can have any number of attributes and child elements which specify the values or settings for the given particular section. To start with, we’ll see the working of some of the most general configuration settings in the Web.config file.

system.web

configuration层次结构中,最常用的是节点system.web 现在我们看一下Web.config 文件中的system.web节点的一些子节点。

Compilation Settings

如果你在使用Visual Studio 2010,默认情况下可能唯一能用的是Compilation节点。如果你想指定the target framework,如果你需要从the Global Assembly Cache (GAC)增加一个程序集(assembly),如果你想将应用程序模式设置成debugging mode,就要用到Compilation settingsThe following code is used to achieve the discussed settings:

<system.web

         <compilation

                 debug="true" strict="true" explicit="true" batch="true"

                 optimizeCompilations="true" batchTimeout="900"

                 maxBatchSize="1000" maxBatchGeneratedFileSize="1000"

                 numRecompilesBeforeAppRestart="15" defaultLanguage="c#"

                 targetFramework="4.0" assemblyPostProcessorType="">

               <assemblies>

                    <add assembly="System, Version=1.0.5000.0, Culture=neutral,

                  PublicKeyToken=b77a5c561934e089"/>

               </assemblies>

</compilation>

</system.web>

assemblies下面,存在属性type, version, culturepublic key token。为了获得一个assemblypublic key token,你需要做以下事情:

  1. Go to Visual Studio tools in the start menu and open the Visual Studio command prompt.
  2. In the Visual Studio command prompt, change the directory to the location where the assembly or .dll file exists.
  3. Use the following command, sn –T itextsharp.dll.
  4. It generates the public key token of the assembly. You should keep one thing in mind that only public key token is generated only for the assemblies which are strongly signed.

Example

C:\WINNT\Microsoft.NET\Framework\v3.5> sn -T itextsharp.dll

Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8

Copyright (c) Microsoft Corporation.  All rights reserved.

 

Public key token is badfaf3274934e0

Explicit and sample attributes are applicable only to VB.NET and C# compiler however ignores these settings.

Page Settings

由于一个ASP.NET应用程序是由很多pages组成,we can set the general settings of a page like sessionstateviewstatebuffer, etc., as shown below:

<pages buffer ="true" styleSheetTheme="" theme ="Acqua"

              masterPageFile ="MasterPage.master"

              enableEventValidation="true">

By using the MasterPageFile and theme attributes, we can specify the master page and theme for the pages in web application.

Custom Error Settings

从名称可知,我们可以配置应用程序级别的错误。Now we will see the description of the customErrors section of the Web.config from the below mentioned code snippet.

<customErrors defaultRedirect ="Error.aspx" mode ="Off">

   <error statusCode ="401" redirect ="Unauthorized.aspx"/>

</customErrors>   

customErrors节点包含defaultRedirectmode属性, 这些属性指定了默认的跳转页面和开/关模式。
customErrors节点的子节点根据error status code可以重新定向到指定页面。

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found
  • 408 Request Timeout

For a more detailed report of status code list, you can refer to this URL:

Location Settings

一个大的项目中,可能有许多文件夹和子文件夹,这种情况下有两种办法配置应用程序。第一种是为每个文件夹和子文件夹配Web.config文件,另一种办法是为整个应用程序配个单一的Web.config第一种方法用起来会比较顺,但如果只有单个的Web.config并且也需要配置应用程序的文件夹和子文件夹那需要怎么做呢?正确的方案是使用Web.config"system.web"节点的"Location"标签。However you can use this tag in either of the discussed methods.

The following code shows you to work with Location settings:

<location path="Login.aspx">

         <system.web>

                 <authorization>

                  <allow users="*"/>

                 </authorization>

         </system.web>

</location>

 

<location path ="Uploads">

    <system.web>

         <compilation debug = "false">

    </system.web>

</location>

In a similar way, you can configure any kind of available settings for any file/folder using the location tag.

Session State and View State Settings

ASP.NET是无状态的。为了维持状态,需要使用ASP.NET的状态管理技巧。View statesession state就是其中之一。For complete information about view state and Session State and how to work with, there are some excellent articles in CodeProject, which you can refer here:

Now we'll see the Web.config settings of View State and Session State:
View State can be enabled or disabled by using the following page settings in the web.config file.

<Pages EnableViewState="false" />

Session state settings for different modes are as shown below:

<sessionState mode="InProc" />

 

<sessionState mode="StateServer"

stateConnectionString= "tcpip=Yourservername:42424" />

 

<sessionState mode="SQLServer" sqlConnectionString="cnn" />

HttpHandler Settings

HttpHandler是一段代码。当一个http请求请求服务器上的某个资源时,代码会执行。例如,请求一个.aspx页面时,ASP.NET页面handler会被执行,类似的if an .asmx file is requested, the ASP.NET service handler is executed. HTTP Handler is a component that handles the ASP.NET requests at a lower level than ASP.NET is capable of handling.

可以创建自己的http handler,用IIS注册它,当有请求时用它来接收消息。For doing this, 只需要创建一个继承于IHttpHanlder的类,然后add the following section of configuration settings in the web.config file For this demonstration, I have created a sample imagehandler class which displays a JPG image to the browser.You can go through the imagehandler class code in the sample download code.

<httpHandlers>

    <add verb="*" path="*.jpg" type="ImageHandler"/>

    <add verb="*" path="*.gif" type="ImageHandler"/>

</httpHandlers/>

HttpModule Settings

HttpModule是一个继承IHttpModule接口的类或程序集,这个接口处理应用程序事件或用户事件。通过实现该接口并用ISS配置,可以创建自己的HttpModuleThe following settings show the HttpModules configuration in the web.config.

<httpModules>

      <add type ="TwCustomHandler.ImageHandler"

           name ="TwCustomHandler"/>

      <remove name ="TwCustomHandler"/>

      <clear />

</httpModules>

Authentication, Authorization, Membership Provider, Role Provider and Profile Provider Settings

These settings are directly available in the web.config file if you have created the ASP.NET application by using the Visual Studio 2010. I'm not going to elaborate them as there are lot of articles in CodeProject describing the functionality and use of these settings and for further information you can refer to them. Some of the links are here:

Authentication Settings

<authentication mode="Forms">

     <forms cookieless="UseCookies" defaultUrl="HomePage.aspx"

                    loginUrl="UnAuthorized.aspx" protection="All" timeout="30">

      </forms>

</authentication>   

Authorization Settings

<authorization

        <allow roles ="Admin"/>

        <deny users ="*"/>

</authorization>       

Membership Provider Settings

<membership defaultProvider="Demo_MemberShipProvider">

         <providers>

            <add name="Demo_MemberShipProvider"

                 type="System.Web.Security.SqlMembershipProvider"

                 connectionStringName="cnn"

                 enablePasswordRetrieval="false"

                 enablePasswordReset="true"

                 requiresQuestionAndAnswer="true"

                 applicationName="/"

                 requiresUniqueEmail="false"

                 passwordFormat="Hashed"

                 maxInvalidPasswordAttempts="5"

                 minRequiredPasswordLength="5"

                 minRequiredNonalphanumericCharacters="0"

                passwordAttemptWindow="10" passwordStrengthRegularExpression="">

         </providers>

</membership>

Role Provider Settings

<roleManager enabled="true" cacheRolesInCookie="true"

cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">

              <providers>

                  <add connectionStringName="dld_connectionstring"

                  applicationName="/" name="Demo_RoleProvider"

                  type="System.Web.Security.SqlRoleProvider, System.Web,

                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

             </providers>

</roleManager>

Profile Provider Settings

<profile defaultProvider="Demo_ProfileProvider">

    <providers>

         <add name="Demo_ProfileProvider" connectionStringName="cnn"

         applicationName="/" type="System.Web.Profile.SqlProfileProvider,

         System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

    </providers>

    <properties>

         <add name="Name" type="String"/>

         <add name="DateofBirth" type="DateTime"/>

         <add name="Place" type="string"/>

    </properties>

</profile>

AppSettings

appSettings节点存储应用程序设置信息,如connection strings, file paths, URLs, port numbers, custom key value pairs, etc.
The following code snippet shows the example of 
appSettings Section:

<appSettings>

         <add key="AppKey" value="APLJI12345AFAFAF89999BDFG"/>

</appSettings>

connectionStrings

The most common section of web.config file the connectionStrings sections allows you to store multiple connection strings that are used in the application. The connectionStrings tag consists of child element with attributes name and connectionstring which is used to identify the connectionstring and the other is used to connect to the database server respectively.

The general connectionstring settings are shown below:

<connectionStrings>

    <add name ="cnn" connectionString ="Initial Catalog = master;

                 Data Source =localhost; Integrated Security = true"/>

</connectionStrings>

ConfigSections

ConfigSections创建自定义的可用在web.config文件中的配置节点。We look at this in the later section of the article, for the time being, we can have look at the configsection settings. ConfigSections节点必须做为configuration 元素的每一个子元素进行声明,否则会报错。

<configSections>

    <sectionGroup name="pageAppearanceGroup">

      <section

        name="pageAppearance"

        type="PageAppearanceSection"

        allowLocation="true"

        allowDefinition="Everywhere"

      />

 </sectionGroup>

 </configSections>

Programmatically Accessing the Web.config File

可以使用C#类来读写Web.config文件中的值。

Reading appSettings values

The following code is used to read the appSettings values from Web.config file. You can use either of the methods shown below:

//Method 1:

        string key = ConfigurationManager.AppSettings["AppKey"];

        Response.Write(key);

 

//Method 2:

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

        KeyValueConfigurationElement Appsetting = config.AppSettings.Settings["AppKey"];

        Response.Write(Appsetting.Key + " <br/>" + "Value:" + Appsetting.Value);

Reading connectionstring values

The following code is used to read the connectionstring values from Web.config file. You can use either of the methods shown below:

//Method 1:

        string cnn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

 

//Methods 2:

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

        ConnectionStringSettings cnnstring;

 

        if (config.ConnectionStrings.ConnectionStrings.Count > 0)

        {

            cnnstring = config.ConnectionStrings.ConnectionStrings["conn"];

            if (cnnstring != null)

                Response.Write("ConnectionString:" + cnnstring.ConnectionString);

            else

                Response.Write(" No connection string");

        }

Reading configuration section values

The following code is used to read the configuration section values from Web.config file. The comments in the code will help you to understand the code:

// Intialize System.Configuration object.

Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

//Get the required section of the web.config file by using configuration object.

CompilationSection compilation =

         (CompilationSection)config.GetSection("system.web/compilation");

//Access the properties of the web.config

Response.Write("Debug:"+compilation.Debug+"<br/>""+

                 "Language:"+compilation.DefaultLanguage);

Update the configuration section values

The following code is used to read the configuration section values from Web.config file:

Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

//Get the required section of the web.config file by using configuration object.

CompilationSection compilation =

         (CompilationSection)config.GetSection("system.web/compilation");

//Update the new values.

compilation.Debug = true;

//save the changes by using Save() method of configuration object.

if (!compilation.SectionInformation.IsLocked)

{

    config.Save();

    Response.Write("New Compilation Debug"+compilation.Debug);

}

else

{

    Response.Write("Could not save configuration.");

}

Encrypt Configuration Sections of Web.config File

As we have already discussed that IIS is configured in such a way that it does not serve the Web.Config to browser, but even in some such situation to provide more security, you can encrypt some of the sections of web.config file. The following code shows you the way to encrypt the sections of web.config file:

Configuration config = WebConfigurationManager.OpenWebConfiguration

                          (Request.ApplicationPath);

ConfigurationSection appSettings = config.GetSection("appSettings");

if (appSettings.SectionInformation.IsProtected)

{

    appSettings.SectionInformation.UnprotectSection();

}

else

{

    appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

}

config.Save();   

Custom Configuration Section in Web.config

I have thought twice before I could put this section of content in this article, as there are a lot of wonderful articles explaining this topic, but just to make this article as complete, I have included this topic too.

Create Custom Configuration Section

The ConfigurationSection class helps us to extend the Web.config file in order to fulfill our requirements. In order to have a custom configuration section, we need to follow the below steps:

Before we actually start working with it, we will have a look at the section settings. We need to have a ProductSection element with child elements gridSettings and color. For this purpose, we will create two classes with the child elements which inherits ConfigurationElement as shown below:

public class GridElement : ConfigurationElement

{

    [ConfigurationProperty("title", DefaultValue = "Arial", IsRequired = true)]

    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\",

                          MinLength = 1, MaxLength = 60)]

    public String Title

    {

        get

        {

            return (String)this["title"];

        }

        set

        {

            this["title"] = value;

        }

    }

 

    [ConfigurationProperty("count", DefaultValue = "10", IsRequired = false)]

    [IntegerValidator(ExcludeRange = false, MaxValue = 30, MinValue = 5)]

    public int Count

    {

        get

        { return (int)this["count"]; }

        set

        { this["size"] = value; }

    }

}

 

public class ColorElement : ConfigurationElement

{

    [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)]

    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;

                 '\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]

    public String Background

    {

        get

        {

            return (String)this["background"];

        }

        set

        {

            this["background"] = value;

        }

    }

 

    [ConfigurationProperty("foreground", DefaultValue = "000000", IsRequired = true)]

    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;

                 '\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]

    public String Foreground

    {

        get

        {

            return (String)this["foreground"];

        }

        set

        {

            this["foreground"] = value;

        }

    }

 

}

... and then we will create a class called ProductSection, for the root element which includes the above child elements.

public class ProductSection : ConfigurationSection

{

    [ConfigurationProperty("gridSettings")]

    public GridElement gridSettings

    {

        get

        {

            return (GridElement)this["gridSettings"];

        }

        set

        { this["gridSettings"] = value; }

    }

 

    // Create a "color element."

    [ConfigurationProperty("color")]

    public ColorElement Color

    {

        get

        {

            return (ColorElement)this["color"];

        }

        set

        { this["color"] = value; }

    }

}

Then finally, we will configure these elements in Web.config file as shown below:

<configSections>

      <section name ="ProductSection" type ="<ProductSection"/>

</configSections>

 

 <ProductSection>

    <gridSettings title ="Latest Products" count ="20"></gridSettings>

    <color background="FFFFCC" foreground="FFFFFF"></color>

 </ProductSection>

Access Custom Configuration Section

The following code is used to access the custom configuration section:

ProductSection config = (ProductSection)ConfigurationManager.GetSection("ProductSection");

string color =config.Color.Background;

string title =config.gridSettings.Title;

int count = config.gridSettings.Count;

Conclusion

In this article, we have learned about the ASP.NET configuration file and we have seen almost all the available and frequently used settings of web.config file. I hope you enjoyed reading this article and this article might have helped you in completing your tasks in some way. Any comments, suggestions and feedback are always welcome, which will help me to write more articles and improve the way in which I present the articles. 

  

 

 

【参考资料 】

HttpModules的认识与深入理解:http://www.csharpwin.com/dotnetspace/3452r3050.shtml

HttpHandlers的认识与加深理解:http://www.csharpwin.com/dotnetspace/3453r1493.shtml

HttpApplication的认识与加深理解:http://www.csharpwin.com/dotnetspace/3451r3186.shtml

HttpRuntime的认识与加深理解:http://www.csharpwin.com/dotnetspace/3450r596.shtml

HttpModules, configSections:http://www.cnblogs.com/serafin/

ASP.NET Zip Entry Handler:http://www.codeproject.com/Articles/25891/ASP-NET-Zip-Entry-Handler

HTTP Handlers and HTTP Modules Overview:http://msdn.microsoft.com/en-us/library/bb398986

http Handlers and http Modules in ASP.NET: http://www.codeguru.com/csharp/.net/net_asp/article.php/c19389/HTTP-Handlers-and-HTTP-Modules-in-ASPNET.htm

Asp.net页面生命周期: http://www.cnblogs.com/yjmyzz/archive/2010/03/28/1698968.html

 

Building a Web Site with Membership and User Login:http://www.codeproject.com/Articles/34444/Building-a-Web-Site-with-Membership-and-User-Login

Always set the "applicationName" property when configuring ASP.NET 2.0 Membership and other Providers:http://weblogs.asp.net/scottgu/archive/2006/04/22/Always-set-the-_2200_applicationName_2200_-property-when-configuring-ASP.NET-2.0-Membership-and-other-Providers.aspx

Creating the Membership Schema in SQL Server (VB):http://www.asp.net/web-forms/tutorials/security/membership/creating-the-membership-schema-in-sql-server-vb

“Your Login Attempt was not Successful. Please Try Again.” - ASP.NET Login Control:http://www.codeproject.com/Articles/27682/Your-Login-Attempt-was-not-Successful-Please-Try

The Searchable SQL Profile Provider:http://www.codeproject.com/Articles/33343/SearchableSqlProfileProvider-The-Searchable-SQL-Pr


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值