ASP.NET编程:听说多是先容 web.config 最具体的文...
另外,小型软件代码重用价值低,没有必要跨平台;大型软件,有严格的规划、部署,不可以随意跨平台。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仍会是最多客户选用的脚本语言,并会在未来几年继续领跑。 最强的技术支持WebService,而且有.NET的所有library做后盾。而且ASP.NET在.NET3.5中还有微软专门为AJAX开发的功能--ASP.NETAJAX。 现在主流的网站开发语言无外乎asp、php、asp.net、jsp等。 在asp.net虚拟主机的服务提供商中,目前首推的是CNNIC的其中一家域名注册机构---时代互联(www.now.net.cn),他们早在2001年微软刚推出Asp.net时就推出了对应的Asp.net虚拟主机了,经笔者的使用测试,他提供的Asp.net性能非常的稳定,版本也会定期的更新,目前他的 现在的ASP.net分为两个版本:1.1和2.0Asp.net1.1用VS2003(visualstudio2003)编程。Asp.net2.0用VS2005(visualstudio2005)编程。现在一般开发用的是VS2003。 asp.net最主要特性包括:◆编程代码更简洁◆网站可实现的功能更强大◆运行效率高◆节省服务器的动作资源 但是java靠开源打出的一片天地,特别是在微软的垄断下能打开今天的局面还是有它的生命力的。 现在的ASP.net分为两个版本:1.1和2.0Asp.net1.1用VS2003(visualstudio2003)编程。Asp.net2.0用VS2005(visualstudio2005)编程。现在一般开发用的是VS2003。 ASP.net1.1和2.0在程序上的语法也有很大不同,现在2.0属于新出来的,不知道半年后会不会有3.0(说笑一下)。Windows2003系统自动支持ASP和ASP.net环境,不用安装任何程序。Asp.net属于编译语言。ASP的最大不同(ASP属于解释语言)。
页:
[1]