在开发中经常会遇到这样的情况,在部署程序时为了保密起见并不将源代码随项目一同发布,而我们开发时的环境与部署环境可能不一致(比如数据库不一样),如果在代码中保存这些配置这些信息部署时需要到用户那里更改代码再重新编译,这种部署方式非常麻烦。
在.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文件的内容:
< configuration >
< configSections >
< section name ="appSettings" type ="AppSettingsSection, requirePermission=/>
< 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 ="windows" type ="IgnoreSection, allowLocation=/>
< 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 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 ="authentication" type ="System.Web.Configuration.AuthenticationSection, " MachineToApplication" />
< section name ="authorization" type ="System.Web.Configuration.AuthorizationSection, />
< section name ="hostingEnvironment" type ="System.Web.Configuration.HostingEnvironmentSection, " MachineToApplication" />
< section name ="httpCookies" type ="System.Web.Configuration.HttpCookiesSection, />
< section name ="membership" type ="System.Web.Configuration.MembershipSection, " MachineToApplication" />
< section name ="mobileControls" type ="System.Web.UI.MobileControls.MobileControlsSection, System.Web.Mobile, />
< 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 ="siteMap" type ="System.Web.Configuration.SiteMapSection, " MachineToApplication" />
< section name ="trace" type ="System.Web.Configuration.TraceSection, />
< section name ="urlMappings" type ="System.Web.Configuration.UrlMappingsSection, " MachineToApplication" />
< section name ="webControls" type ="System.Web.Configuration.WebControlsSection, />
< 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, />
< 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 =/>
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, />
<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文件的内容:
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的所有节点:
web.confg的示例文件:
< 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 >
< add key ="WebDAL" value ="PetShop.SQLServerDAL" />
< add key ="OrdersDAL" value ="PetShop.SQLServerDAL" />
< add key ="ProfileDAL" value ="PetShop.SQLProfileDAL" />
< add key ="EnableCaching" value ="true" />
< add key ="CategoryCacheDuration" value ="12" />
< add key ="ProductCacheDuration" value ="12" />
< add key ="ItemCacheDuration" value ="12" />
< add key ="CacheDependencyAssembly" value ="PetShop.TableCacheDependency" />
< add key ="CacheDatabaseName" value ="MSPetShop4" />
< add key ="CategoryTableDependency" value ="Category" />
< add key ="ProductTableDependency" value ="Product,Category" />
< add key ="ItemTableDependency" value ="Product,Category,Item" />
< add key ="OrderStrategyAssembly" value ="PetShop.BLL" />
< add key ="OrderStrategyClass" value ="PetShop.BLL.OrderSynchronous" />
< add key ="OrderMessaging" value ="PetShop.MSMQMessaging" />
< add key ="OrderQueuePath" value ="FormatName:DIRECT=OS:MachineName\Private$\PSOrders" />
< add key ="Event Log Source" value =".NET Pet Shop 4.0" />
appSettings >
< system.web >
< pages theme ="PetShop" styleSheetTheme ="PetShop" />
< compilation debug ="false" >
compilation >
< authentication mode ="Forms" >
< forms name ="PetShopAuth" loginUrl ="SignIn.aspx" protection ="None" timeout ="60" />
authentication >
< 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 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 >
< 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. 本文包括以下几方面内容:
- Web.config sections/settings
- Reading Web.config
- Writing or manipulating Web.config
- Encrypting the Web.config and
- 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>
从上面的树结构可知,标签configuration是Web.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 settings。The following code is used to achieve the discussed settings:
<system.web
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, culture和public key token。为了获得一个assembly的public key token,你需要做以下事情:
- Go to Visual Studio tools in the start menu and open the Visual Studio command prompt.
- In the Visual Studio command prompt, change the directory to the location where the assembly or .dll file exists.
- Use the following command, sn –T itextsharp.dll.
- 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 sessionstate, viewstate, buffer, 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节点包含defaultRedirect和mode属性, 这些属性指定了默认的跳转页面和开/关模式。
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:
- http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
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 state和session 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:
- Beginners Introduction to State Management Techniques in ASP.NET
- Exploring Session in ASP.NET
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配置,可以创建自己的HttpModule。The 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:
- ASP.NET Membership and Role Provider
- Developing custom ASP.NET Membership and Role providers reading users from custom section in theweb.config
- ASP.NET Membership
- Membership and Role providers for MySQL
- Custom Membership, Role Providers, Website administration tool, and Role based access to individual files
Authentication Settings
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
forms>
authentication>
Authorization Settings
<authorization
<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 + "
" + "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+"
""+
"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 ="
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