|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
另外,小型软件代码重用价值低,没有必要跨平台;大型软件,有严格的规划、部署,不可以随意跨平台。web|参考Web.ConfigWrittenon:Nov,16th2001.
Application("DSN")="Server=moon;Driver=SqlServer;Database=Store;UID=user;PWD=bingo;"
Abovedeclarationintheglobal.asafilemightbefamiliartoalmostallASPprogrammers.
WhilegoingthroughtheMSDN,Iwasoverwhelmed,bylookingintotheweb.configfilewhichhandlesallconfigurationforanapplication.ThereplacementfortheabovedeclarationinASP.NETisasfollows:
<configuration>
<appSettings>
<addkey="DSN"value="Server=moon;database=Store;Trusted_Connection=yes"/>
</appSettings>
</configuration>
Then,inyourASPXpage,youshouldhavethefollowingstatementtoretrievethevalueforDSN.
DimdsnAsString=ConfigurationSettings.AppSettings("DSN")
So,Istartedtoaskthefollowingquestionstomyself.
Whatexactlyisweb.config?
Doesthishandlesonlytheaboveexample?
Whatarethebenefitsofweb.config?
And,followingweretheresultsformyquestions,andIwouldliketosharewithyouall.ThisisbasedonBeta2
Introduction
Well,web.configisaXML-basedconfigurationfile.Ifyouseetheaboveexample,youcanmakesurethatalltheelementsarebasedonXMLstandards.Obviously,wecandevelopatoolformodifyingandeditingthisconfigurationfile.
Aweb.configcanappearinanydirectoryonanASP.NETWebapplicationserver.Saidthis,ifyouhaveaweb.configfileinthedirectory"c:inetpubwwwroot",thenthesettingsspecifiedintheweb.configisapplicabletoallthesubdirectoriesunderwwwroot.Eachsub-directorycanhaveitsownweb.configfileanditwilloverwritethesettingsoftheweb.configfileintheparentdirectory.
Thereisanotherfilecalledmachine.config,whichprovidesconfigurationsettingsfortheentireserver.Ifyouchangethecontentsofanyweb.configfilethenthechangewillbeimmediatelyreflectedintheprocessingofanyincomingrequeststothewebserver.Thesesettingsarecalculatedonlyonceandthencachedacrosssubsequentrequests.ASP.NETautomaticallywatchesforfilechangesandwillinvalidatethecacheifanyoftheconfigurationfileschange.(FormoreinformationoncachingClickhere)
Therootelementofaweb.configfileisalwaysa<configuration>tag.The<configuration>tagcontainsthreedifferenttypesofelements:1)configurationsectionhandlerdeclarations,2)configurationsectiongroups,and3)configurationsectionsettings.
FollowingarethelistofcommonlyusedConfiguationtags,that,webeusedinourwebapplicationsandwillgothruthem
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>
Thiscanbedeclaredatthemachine,site,applicationandsubdirectorylevelIncludeallthecustomsettingsforyourapplicationinthissection.Appsettingstagcontainstwoattributesviz;keyandvalue.
<addkey="key"value="value"/>
Eg:<addkey="DSN"value="Server=moon;database=Store;Trusted_Connection=yes"/>
<authentication>
Alltheauthentication/securityrelatedstuffaredeclaredinthissection.Authenticationsectioncontainsasingleattributecalled"mode".Possiblevaluesfor"mode"are(a)Forms(b)None(c)Passportand(d)Windows
Formbasedauthenticationcanbeused,ifyouwanttouseASP.NETforms-basedauthentication.
Ifyouwanttoallowanyonmyoususerstoaccessyourwebsite,selectnone.
Passpostauthenticationcanbeused,ifyouwanttheauthenticationtobebasedonMicrosoftPassportauthenticationmode.
Usewindowsmodeauthentication,ifyouwanttouseBasic,Digest,IntegratedWindowsauthentication(NTLM/Kerberos),orcertificates
Note:IfyouareusingFormbasedauthentication,thenyouhaveseveralotheroptionssuchashowthepasswordshouldbeencrypted,whilesubmittingtheform,ifloginfails,whichpageshouldbeshowntotheuseretc.
AstheAuthenTicationisincludedin,System.Web.Configuration.AuthenticationConfigHandlerwhilesettingtheauthenticationmode,youshouldcodeasfollows
Eg:
<configuration>
<system.web>
<authenticationmode="None"/>
</system.web>
</configuration>
<authorization>
Thisisaverypowerfultag,wereyoucanrestrictorallowuserswhowishtovisityourwebsite.Authorizationtagcontainstwosubtagssuchasallowanddeny.
Allowtagprovidesuswiththreeattributes,namelyusers,rolesandverbs.Wecanaddthelistofusersseperatedbycommaintheusersattribute.Alsowecanspecifytheroleinwhicheachuserbelongstoo.Importantaspectoftheattributeverbisthat,wecancontrolusersdependinguponthewebrequestthattheserverisgetting.TheverbattributeprovidesuswithfouroptionsGET,HEAD,POSTandDEBUG.
Denytaghasthesameattributesastheallowtaghas.Otheraspectofboththesetagsare,wecanusetwospecialsymbols?and*tospecifyanonymoususersand"allusers"respectively.
Eg:
<configuration>
<system.web>
<authorization>
<allowroles="Admins"/>
<denyusers="*"/>
</authorization>
</system.web>
</configuration>
<compilation>
Itisinthistag,yousetallyourcompilcationoptions.Thistagcontainsthreesub-tagsandsevenattributes,whicharediscussedbelow.
Attributes
debugspecifieswhethertocompileretailbinariesordebugbinaries.TruespecifiesdebugbinariesandFalsespecifiesRetailbinaries
defaultLanguagecanbeusedtospecifythelanguagenamestouseindynamiccompilationfiles.
useexplicitattributetoturnonexplicitoptionortoturnoff.Thistakeseithertrueorfalse,weretruemeansexplicitisenabled.
Wecanalsodoabatchcompiliationbyspecifyingtheattributebathastrue.Ifwehavebatchcompiliation,thenwemightfacethetimeoutproblem.ThenwemayalsowanttousethebatchTimeoutattributetosetthetimeforbatchtimeout.
numRecompilesBeforeApprestartisthenextattribute.Thisattributeindicatesthenumberofdynamicrecompilesofresourcesthatcanoccurbeforetheapplicationrestarts.Thisattributeissupportedattheglobalandapplicationlevelbutnotatthedirectorylevel.
Strictattributeindicatesthesettingsofthevisualbasicstrictcompileoption.supportstwovalues,TRUEandFALSE.
SubTags
Compilerstagcontainsmanyoronecompilertag,werewedefinenewcompileroptions.AssembliesandNamespacesspecifiesASP.NETprocessingdirectives
Eg:
<configuration>
<system.web>
<compilationdefaultLanguage="VB"debug="true">
<compilers>
<compilerlanguage="VB;VBScript"extension=".cls"type="Microsoft.VB.VBCodeProvider,System"/>
<compilerlanguage="C#;Csharp"extension=".cs"type="Microsoft.CSharp.CSharpCodeProvider,System"/>
</compilers>
<assemblies>
<addassembly="ADODB"/>
<addassembly="*"/>
</assemblies>
<namespaces>
<addnamespace="System.Web"/>
<addnamespace="System.Web.UI"/>
<addnamespace="System.Web.UI.WebControls"/>
<addnamespace="System.Web.UI.HtmlControls"/>
</namespaces>
</compilation>
</system.web>
</configuration>
<customErrors>
Asthenamesaysallabout,customErrosprovidesinformationaboutcustomerrormessagesforanASP.NETapplication.CustomErrorstagprovidesuswiththreeattributes.
defaultRedirectcanbeusedtospecifytheURLtodirectabrowser,ifanyunexpectederroroccurs.ThemodeattributetakesthreevaluesOn,OfforRemoteOnly.Remeteonlyspecifiesthatcustomerrorsareshownonlytoremoteclients.
Thesubtag<error>mightbeveryusefulinavarietyofway.Wecanspecifytheerrorstatuscodeandaskthebrowsertoredirecttoaspecificpage.Weshouldusetheattribute,statusCodetospecifytheerrorstatuscodeandtheredirectattributetospecifytheredirectURL.
Eg:
<configuration>
<system.web>
<customErrorsdefaultRedirect="error.aspx"mode="RemoteOnly">
<errorstatusCode="500"redirect="InternalError.htm"/>
</customErrors>
</system.web>
</configuration>
<globalization>
Configurestheglobalizationsettingsofanapplication.TwoimportantattributesofthistagarerequestEncodingandresponseEncoding.Defaultvaluesforbothencodingare"iso-8859-1",whichisEnglish.
Eg:
<configuration>
<system.web>
<globalizationrequestEncoding="iso-8859-1"responseEncoding="iso-8859-1">
<globalization/>
</system.web>
</configuration>
<identity>
ControlstheapplicationidentityoftheWebapplication.Supportsthreeattributes.Impersonateisthefirstattribute,whichspecifieswhetherclientimpersonationisusedoneachrequesttothewebserver.TakeseitherTRUEorFALSE.IftheimpersonationisFALSE,thenweshouldspecifythevaluesfortheattributes,usernameandpassword.
Eg:
<configuration>
<system.web>
<identityimpersonate="true"/>
</system.web>
</configuration>
<machineKey>
ConfigureskeystouseforencryptionanddecryptionofFormsauthenticationcookiedata.Thissectioncanbedeclaredatthemachine,site,andapplicationlevelsbutnotatthesubdirectorylevel.Thistagsupportsthreeattributes;validationKey,decryptionKeyandvalidation.
ValidationKeyandDecryptionKeytakesthedefaultvalue,whichisAutoGenerate.Wecanalsospecifyakeyanditshouldbelengthof128hexadecimalcharacters.Thevalidationattributecanbeusedtospecifythealogrithmtobeusedwhileencryption.PossiblevaluesareSHA1,MD5and3DES.
<pages>
Asthenameindicates,weshouldusethistagtospecifythepage-specificconfigurationsettings.Itsupportssixattributes.Wewilldicsusseachoneofthem.
Bufferattributespecifies,whetherresourcesarebufferedornot.ThistakesthreevaluesOn,OffandReadonly.
Wecanenablethesessionstateordisablethesessionbyusingtheattribute,enableSessionState.Thistakestwovalues,eitherTRUEorFALSE.
pageBaseTypecanbeusedtospecifycode-behindclassthatan.aspxpageinherits.userControlBaseTypespecifiesacodebehindclassthatUserControlsinherit.
Ifyouwanttodisableanyeventfiringinthepage,youcanusetheattributeautoEventWireup.ThistootakeseitherTRUEorFALSE.
Eg:
<configuration>
<system.web>
<pagesbuffer="true"enableSessionState="true"autoEventWireup="true">
</pages>
</system.web>
</configuration>
<processModel>
ThissectionismainlyfortheWebAdministrators.Weshouldusethistagresponsibly.Wecanuseusetagtospecifythetimeoutforwhenanewworkerprocessshouldstartinplaceofcurrentone,theidleTimeoutwhichspecifiestheminutesthatASP.NETautomaticallyshutsdowntheworkerprocess.OneoftheimportantattributeofthistagisrequestQueueLimit,wereyoucanspecifythenumberofrequestsallowedinthequeuebeforeASP.NETbeginsreturning"503"(Servertoobusyerror).Defaultis5000.
Eg:
<configuration>
<system.web>
<processModelenable="true"timeout="10"idleTimeout="20"requestQueueLimit="100">
</processModel>
</system.web>
</configuration>
<sessionState>
Thistagcanbeusedtospecify,werewearestoringthesession.Thiscanbespecifiedinthemodeattribute.SupportedvaluesmodeareOff,InProc,StateServerandSqlServer.InProcindicatesthat,sessionstatesisstoredlocally.StateServerindicatesthatsessionstateisstoredonaremoteserverandsqlservercanbeusedtoindicatethatthesessionstateisstoredonasqlserver.
Wealsohavethechoicetousecookiestostorethesessions.Thiscanbesetusingtheattributecookieless.Sessiontimeoutcanbespecifiedusingtheattributecalledtimeout.Bydefault,thesessiontimeoutis20minutes(sameasclassicASP).
Eg:
<configuration>
<system.web>
<sessionStatemode="Inproc"cookieless="true"timeout="20">
</sessionState>
</system.web>
</configuration>
<trace>
Thisisaveryusefultagtodebugourprograms.Wecanusethetracetagtoshowalltheinformationforthepageprocessedbytheserver.Bydefault,allthetracesarestoredontheserver.WecanspecifythenumberoftracesstoredinthememorybyusingtheattributecalledrequestLimit.Defaultis10.Wecaneitherappendthetracetothepageorcanbeviewedusingthetraceutility.ThisisspecifiedbytheattributecalledpageOutput.
Eg:
<configuration>
<system.web>
<traceenabled="false"requestLimit="15"pageOutput="true">
</trace>
<system.web>
</configuration>
Therearesomemoretagsavailablewhichcanbeusedintheweb.configfile.Thoseare<httpHandlers>,<httpModules>,<httpRuntime>,<securityPolicy>,<webServices>,<trust>and<browserCaps>.Youmaywanttolookintothese.
Summary
Thatwasasmallintroductionforweb.configfile.Andtoendwith,Ihavetwotipsforyou.
Suppose,ifwearecreatinganewfolderandifwewanttooverridetheconfigurationsettingsoftheparentfolder,whatwehavetodoisjustcreateanotherweb.configfileinthesub-directory.Ifweneedtopreventtheoverridingofthenewweb.configfileinthesubdirectory,thenwecanaddtheattributeallowOverrideinthelocationtag.Also,wecanspecifytheapplicationnameintheattributepath.
<configuration>
<locationpath="app1"allowOverride="false">
<system.web>
<identityimpersonate="false"userName="app1"password="app1pw"/>
</system.web>
</location>
</configuration>
Whatifsomeonetypestheweb.configfileintheURL?
ASP.NETconfiguresIIStopreventdirectbrowseraccesstoweb.configfilestoensurethattheirvaluescannotbecomepublic(attemptstoaccessthemwillcauseASP.NETtoreturn403:AccessForbidden).
ExternalLinks
http://www.123aspx.com/directory.aspx?dir=85
http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconcreatingnewsectionhandlers.asp
在经过全球个人PC市场占有90%的微软对asp.net不断优化与整合后,asp.net与微软自身平台的动用上更加的高效,加上asp.net在应用上非常容易上手,相信asp.net仍会是最多客户选用的脚本语言,并会在未来几年继续领跑。 |
|