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


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM