Web.config配置詳解 (轉)

application("dsn") = "server=moon; driver=sql server; database=store; uid=user; pwd=bingo;"
above declaration in the global.asa file might be familiar to almost all asp programmers.

while going through the msdn, i was overwhelmed, by looking into theweb.config file which handles all configuration for an application. thereplacement for the above declaration in asp .net is as follows:

<configuration>
<appsettings>
<add key="dsn" value="server=moon;database=store;trusted_connection=yes" />
</appsettings>
</configuration>


then, in your aspx page, you should have the following statement to retrieve the value for dsn.

dim dsn as string = configurationsettings.appsettings("dsn")

so, i started to ask the following questions to myself.

what exactly is web.config?
does this handles only the above example?
what are the benefits of web.config?


and, following were the results for my questions, and i would like to share with you all. this is based on beta2


introduction

well, web.config is a xml-based configuration file. if you see theabove example, you can make sure that all the elements are based on xmlstandards. obviously, we can develop a tool for modifying and editingthis configuration file.

a web.config can appear in any directory on an asp.net web applicationserver. said this, if you have a web.config file in the directory"c:/inetpub/wwwroot", then the settings specified in the web.config isapplicable to all the subdirectories under wwwroot. each sub-directorycan have its own web.config file and it will overwrite the settings ofthe web.config file in the parent directory.

there is another file called machine.config, which providesconfiguration settings for the entire server. if you change thecontents of any web.config file then the change will be immediatelyreflected in the processing of any incoming requests to the web server.these settings are calculated only once and then cached acrosssubsequent requests. asp.net automatically watches for file changes andwill invalidate the cache if any of the configuration files change.(for more information on caching click here)

the root element of a web.config file is always a <configuration>tag. the <configuration> tag contains three different types ofelements: 1) configuration section handler declarations, 2)configuration section groups, and 3) configuration section settings.

following are the list of commonly used configuation tags, that, we be used in our web applications and will go thru them

1) appsettings
2) authentication
3) authorization
4) compilation
5) customerrors
6) globalization
7) identity
8) machinekey
9) pages
10) processmodel
11) sessionstate
12) trace


<appsettings>
this can be declared at the machine, site, application and subdirectorylevel include all the custom settings for your application in thissection. appsettings tag contains two attributes viz; key and value.

<add key="key" value="value"/>
eg: <add key="dsn" value="server=moon;database=store;trusted_connection=yes" />


<authentication>
all the authentication/security related stuff are declared in thissection. authentication section contains a single attribute called"mode". possible values for "mode" are (a) forms (b) none (c) passportand (d) windows

form based authentication can be used, if you want to use asp .net forms-based authentication.

if you want to allow anyonmyous users to access your website, select none.

passpost authentication can be used, if you want the authentication to be based on microsoft passport authentication mode.

use windows mode authentication, if you want to use basic, digest,integrated windows authentication (ntlm/kerberos), or certificates

note: if you are using form based authentication, then you have severalother options such as how the password should be encrypted, whilesubmitting the form, if login fails, which page should be shown to theuser etc.

as the authentication is included in,system.web.configuration.authenticationconfighandler while setting theauthentication mode, you should code as follows

eg:
<configuration>
<system.web>
<authentication mode="none" />
</system.web>
</configuration>




<authorization>
this is a very powerful tag, were you can restrict or allow users whowish to visit your web site. authorization tag contains two sub tagssuch as allow and deny.

allow tag provides us with three attributes, namely users, roles andverbs. we can add the list of users seperated by comma in the usersattribute. also we can specify the role in which each user belongs too.important aspect of the attribute verb is that, we can control usersdepending upon the web request that the server is getting. the verbattribute provides us with four options get, head, post and debug.

deny tag has the same attributes as the allow tag has. other aspect ofboth these tags are, we can use two special symbols ? and * to specifyanonymous users and "all users" respectively.

eg:
<configuration>
<system.web>
<authorization>
<allow roles="admins" />
<deny users="*" />
</authorization>
</system.web>
</configuration>




<compilation>
it is in this tag, you set all your compilcation options. this tagcontains three sub-tags and seven attributes, which are discussedbelow.

attributes
debug specifies whether to compile retail binaries or debug binaries.true specifies debug binaries and false specifies retail binaries

defaultlanguage can be used to specify the language names to use in dynamic compilation files.

use explicit attribute to turn on explicit option or to turn off. thistakes either true or false, were true means explicit is enabled.

we can also do a batch compiliation by specifying the attribute bath astrue. if we have batch compiliation, then we might face the timeoutproblem. then we may also want to use the batchtimeout attribute to setthe time for batch timeout.

numrecompilesbeforeapprestart is the next attribute. this attributeindicates the number of dynamic recompiles of resources that can occurbefore the application restarts. this attribute is supported at theglobal and application level but not at the directory level.

strict attribute indicates the settings of the visual basic strict compile option. supports two values, true and false.

subtags
compilers tag contains many or one compiler tag, were we define newcompiler options. assemblies and namespaces specifies asp .netprocessing directives

eg:
<configuration>
<system.web>
<compilation defaultlanguage="vb" debug="true">
<compilers>
<compiler language="vb;vbscript" extension=".cls" type="microsoft.vb. vbcodeprovider,system" />
<compiler language="c#;csharp" extension=".cs" type="microsoft.csharp. csharpcodeprovider,system" />
</compilers>
<assemblies>
<add assembly="adodb" />
<add assembly="*" />
</assemblies>
<namespaces>
<add namespace="system.web" />
<add namespace="system.web.ui" />
<add namespace="system.web.ui.webcontrols" />
<add namespace="system.web.ui.htmlcontrols" />
</namespaces>
</compilation>
</system.web>
</configuration>




<customerrors>
as the name says all about, customerros provides information aboutcustom error messages for an asp.net application. customerrors tagprovides us with three attributes.

defaultredirect can be used to specify the url to direct a browser, ifany unexpected error occurs. the mode attribute takes three values on,off or remoteonly. remeteonly specifies that custom errors are shownonly to remote clients.

the subtag <error> might be very useful in a variety of way. wecan specify the error status code and ask the browser to redirect to aspecific page. we should use the attribute, statuscode to specify theerror status code and the redirect attribute to specify the redirecturl.

eg:
<configuration>
<system.web>
<customerrors defaultredirect="error.aspx" mode="remoteonly">
<error statuscode="500" redirect="internalerror.htm"/>
</customerrors>
</system.web>
</configuration>




<globalization>
configures the globalization settings of an application. two importantattributes of this tag are requestencoding and responseencoding.default values for both encoding are "iso-8859-1", which is english.

eg:
<configuration>
<system.web>
<globalization requestencoding="iso-8859-1" responseencoding="iso-8859-1">
<globalization/>
</system.web>
</configuration>




<identity>
controls the application identity of the web application. supportsthree attributes. impersonate is the first attribute, which specifieswhether client impersonation is used on each request to the web server.takes either true or false. if the impersonation is false, then weshould specify the values for the attributes, username and password.

eg:
<configuration>
<system.web>
<identity impersonate="true" />
</system.web>
</configuration>




<machinekey>
configures keys to use for encryption and decryption of formsauthentication cookie data. this section can be declared at themachine, site, and application levels but not at the subdirectorylevel. this tag supports three attributes; validationkey, decryptionkeyand validation.

validationkey and decryptionkey takes the default value, which isautogenerate. we can also specify a key and it should be length of 128hexadecimal characters. the validation attribute can be used to specifythe alogrithm to be used while encryption. possible values are sha1,md5 and 3des.




<pages>
as the name indicates, we should use this tag to specify thepage-specific configuration settings. it supports six attributes. wewill dicsuss each one of them.

buffer attribute specifies, whether resources are buffered or not. this takes three values on, off and readonly.

we can enable the session state or disable the session by using theattribute, enablesessionstate. this takes two values, either true orfalse.

pagebasetype can be used to specify code-behind class that an .aspxpage inherits. usercontrolbasetype specifies a code behind class thatusercontrols inherit.

if you want to disable any event firing in the page, you can use theattribute autoeventwireup. this too takes either true or false.

eg:
<configuration>
<system.web>
<pages buffer="true" enablesessionstate="true" autoeventwireup="true">
</pages>
</system.web>
</configuration>




<processmodel>
this section is mainly for the web administrators. we should use thistag responsibly. we can use use tag to specify the timeout for when anew worker process should start in place of current one, theidletimeout which specifies the minutes that asp .net automaticallyshuts down the worker process. one of the important attribute of thistag is requestqueuelimit, were you can specify the number of requestsallowed in the queue before asp .net begins returning "503" (server toobusy error). default is 5000.

eg:
<configuration>
<system.web>
<processmodel enable="true" timeout="10" idletimeout="20" requestqueuelimit="100">
</processmodel>
</system.web>
</configuration>




<sessionstate>
this tag can be used to specify, were we are storing the session. thiscan be specified in the mode attribute. supported values mode are off,inproc, stateserver and sqlserver. inproc indicates that, sessionstates is stored locally. stateserver indicates that session state isstored on a remote server and sqlserver can be used to indicate thatthe session state is stored on a sql server.

we also have the choice to use cookies to store the sessions. this canbe set using the attribute cookieless. session timeout can be specifiedusing the attribute called timeout. by default, the session timeout is20 minutes (same as classic asp).

eg:
<configuration>
<system.web>
<sessionstate mode="inproc" cookieless="true" timeout="20">
</sessionstate>
</system.web>
</configuration>




<trace>
this is a very useful tag to debug our programs. we can use the tracetag to show all the information for the page processed by the server.by default, all the traces are stored on the server. we can specify thenumber of traces stored in the memory by using the attribute calledrequestlimit. default is 10. we can either append the trace to the pageor can be viewed using the trace utility. this is specified by theattribute called pageoutput.

eg:
<configuration>
<system.web>
<trace enabled="false" requestlimit="15" pageoutput="true">
</trace>
<system.web>
</configuration>




there are some more tags available which can be used in the web.configfile. those are <httphandlers>, <httpmodules>,<httpruntime>, <securitypolicy>, <webservices>,<trust> and <browsercaps>. you may want to look into these.


summary
that was a small introduction for web.config file. and to end with, i have two tips for you.

suppose, if we are creating a new folder and if we want to override theconfiguration settings of the parent folder, what we have to do is justcreate another web.config file in the sub-directory. if we need toprevent the overriding of the new web.config file in the subdirectory,then we can add the attribute allowoverride in the location tag. also,we can specify the application name in the attribute path.

<configuration>
<location path="app1" allowoverride="false">
<system.web>
<identity impersonate="false" username="app1" password="app1pw" />
</system.web>
</location>
</configuration>



what if some one types the web.config file in the url?

asp.net configures iis to prevent direct browser access to web.configfiles to ensure that their values cannot become public (attempts toaccess them will cause asp.net to return 403: access forbidden).

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章