Tải bản đầy đủ - 0 (trang)
Chapter 5: Configuring an ASP.NET Application

Chapter 5: Configuring an ASP.NET Application

Tải bản đầy đủ - 0trang

Overview

Inthischapter,youwilllearnhowto:

EditASP.NETconfigurationfiles.

ConfigureanASP.NETapplication.

Overrideparentconfigurationsettings.

Lockdownconfigurationsettings.

OneofthemostimportantnewfeaturesofASP.NET,giventhe

advantagesitprovidesdevelopers,isitsnewconfigurationsystem.This

configurationsystemuseshuman-andmachine-readableXML-based

filestostoreconfigurationinformation.Thischapterwilllookathowthese

configurationfilesworkandhowyoucanusetheminyourapplications.



UnderstandingASP.NETConfiguration

ConfigurationinASP.NETisbasedonaseriesofXML-basedfilesthat

arehierarchicalinnature.Eachservercontainsamaster(orroot)

configurationfilecalledmachine.configthatisstoredatthepath

%windir%\Microsoft.NET\

Framework\%version%\CONFIG\machine.config.(Seethefollowing

illustration,whichshowshowthepathwouldlookfortheVisualStudio

.NETFinalBetaonWindowsServer2003.Theversionnumberforthe

finalreleasewillbedifferent.)Thismasterconfigurationfilecontainsthe

defaultsettingsforallASP.NETapplicationsonthatserver.Thisfilealso

containssettingsformachine-wideconfiguration(suchasassembly

bindingandremotingchannels),aswellasothersettings.Usecaution

whenyoueditthisfiletoavoidinadvertentlymakingchangesthataffect

otherapplications.



Inadditiontomachine.config,eachASP.NETWebapplicationcanhave

oneormorefilescalledWeb.config(oneperfolder)initsfolderhierarchy.

EachWeb.configfileoverridesanysettingsoftheconfigurationfilesin

parentfolders.SettingsinWeb.configapplyonlytocontentwithinthe

folderinwhichthefileresides,andanycontentinchildfolders.This

allowsyoutosetupahierarchyofconfigurationfilesthatletsyouset

application-wideconfigurationoptionsatthehighestlevels,whilestill

allowingyoutooverridethosesettingsatalowerlevel.Forexample,if

youhaveagroupoffileswhoseaccessmustberestricted,youcanplace



thosefilesinaseparatefolderwithinyourapplicationandthenadda

Web.configfilethatimplementstightersecurityrestrictions.Youllseehow

todothislaterinthischapter.

Note Ifyoudecidetousemultiplelevelsofconfigurationfileswithin

yourapplication,youshouldconsiderusingcommentstomake

itclearwhereyoureoverridingsettingsfromparentWeb.config

filesorfrommachine.config.Thisway,thosewhoneedto

maintaintheapplicationcanunderstandyourintent.Comments

inASP.NETconfigurationfilesusethesamesyntaxasHTML

comments:.

Keepinmindalsothatmanyofthesettingsconfiguredin

Web.configandmachine.configcanalsobeoverriddenatthe

pagelevelusingattributesofthe@Pagedirective.Takecare

toensurethatalldevelopersonaproject(aswellasthosewho

willmaintaintheapplication)understandthis,toavoid

confusion.

Changestoconfigurationfilesettingsaredetectedautomaticallybythe

ASP.NETruntimeandintegratedintothecachedconfigurationsettings

fortheapplication.Whenachangeismade,allnewrequestsfor

resourceswithinthescopeofagivenconfigurationfileusethenew

configurationsettingsautomatically.



IntroducingWeb.config

Likethemachine.configfile,Web.configisXMLbased.Thismeansthat

eachWeb.configfileismadeupoftagsandattributes,similartoHTML.

(XMLisamarkuplanguagebasedonStructuredGeneralizedMarkup

Language,orSGML,thesamelanguageHTMLisbasedon.)Unlike

machine.config,however,mostWeb.configfileswillnotcontainelements

foreveryavailableconfigurationsetting.Infact,anASP.NETapplication

doesntactuallyrequireaWeb.configfileinordertofunction.If

Web.configisomittedfromanapplication,itsimplyinheritsits

configurationsettingsfromthemasterconfigurationfile,machine.config.



AWeb.configfilehasthefollowingbasicstructure:


EachWeb.configfileshouldbeginwiththestandardXMLdeclaration,

thoughitwillworkwithoutit.Thefilealsocontainsopeningandclosing

tags.Nestedwithinthosetagsaretheopeningand

closingtags,indicatingthatthecontentwithinisASP.NETspecificconfigurationinformation.Thisconfigurationinformationis

suppliedintagsreferredtoaselements.Eachelementconsistsofan

openingandclosingtag.Anyattributesaredefinedwithintheopeningtag

andanychildelementsaredefinedbetweentheopeningandclosing

tags.Ifanelementdoesnthavechildelements,youcanomittheclosing

tagbyaddingtheforwardslash(/)characterattheendoftheopening

tag.(ThisisstandardXMLsyntax.)Youllseethisformatinactionlaterin

thischapter,aswellasinAppendixB.

Note ManydevelopersfounditfrustratingwhenMicrosoftVisual

InterDev6reformattedcodeaccordingtoitspreferredstyle.

Thatfeaturewasdifficult,ifnotimpossible,toturnoff.In

MicrosoftVisualStudio.NET,notonlycanyoucontrolhow

codeisvalidatedandformatted,butinmostcasesyoucanalso

turnoffautoformattingentirely.

Tovieworchangetheformattingsettingsforagivenlanguage,

fromtheToolsmenuselectOptions,andthenclicktheText

Editorfolder.Clickthefolderforthelanguageofyourchoice.



Notethatforsomelanguages,theformattingsettingsappear

onmorethanoneoptionpage.Forexample,HTML/XML

formattingoptionsaresetontheFormatpage,theHTML

Specificpage,andtheXMLSpecificpage,allunderthe

HTML/XMLfolder.



EditingConfigurationFiles

Atthetimeofthiswriting,theVisualStudio.NETenvironmentstoolsfor

editingconfigurationfilesarelimitedtosyntaxcoloring,XMLvalidation,

andcodeformatting.BecausetheASP.NETconfigurationfilesareXML

based,youcanalsouseyourfavoriteXMLeditor(ortexteditor)toedit

them.



OpenWeb.config

1. EitheropentheChapter_05projectfromthepracticefiles,or

createanewprojectnamedChapter_05,usingthestepsyou

learnedinChapter2.

2. LocatetheWeb.configfileintheSolutionExplorerwindowand

double-clickit.

TheWeb.configfilewillbeopenedforeditingusingtheVisual

Studio.NETXMLeditor,asshownintheillustrationonthe

followingpage.Welllookatexamplesofeditingthisfilelaterin

thechapter,soyoumightwanttoleaveitopen.



Inadditiontosyntaxcoloringandvalidation,VisualStudio.NETprovides

adefaultWeb.configfileforeachnewWebapplicationprojectthatyou

create.Thisdefaultfilecontainsthemostcommonlyusedelements,as

wellascommentsthatexplaintheavailableoptionsforeachelement,as

showninthepreviousillustration.ThedefaultWeb.configfileisusefulas

atemplateforanyadditionalWeb.configfilesyouwanttoplacein

subfoldersofyourWebapplication.Keepinmindthatwhenyoureusing

configurationfilesinsubfoldersofyourapplication,itsagoodideato

includeonlytheelementsfortheconfigurationsettingsfromtheparent

filethatyouwanttooverride.Thishelpspreventtheaccidentaloverriding

ofaconfigurationsetting,anditmighthelpreduceparsingoverheadfor

theconfigurationofyourapplication.



EditingtheMasterConfigurationFile

Notonlydoesthemasterconfigurationfile,machine.config,containthe

defaultsettingsforallASP.NETapplicationsonthemachine,butitalso

hasmachine-wideconfigurationsettings.Becautiouswheneditingthis

file.Itisprudenttocreateabackupcopyofthefilebeforeyoueditit.Also

keepinmindthatunlessyouretheonlyonewhousesthemachineon

whichyouredeveloping,anychangesthatyoumaketomachine.config

willalsoaffectotherASP.NETdevelopersusingthemachine.Unlessyou

enjoydealingwithunhappycolleagues,youshoulddiscussanyproposed

changeswiththemfirst.



ConfiguringanASP.NETApplication

Atthetimeofthiswriting,noGUItoolsareavailableforeditingthe

Web.configfilesandmodifyingconfigurationsettings.Fortunately,the

defaultWeb.configfilecreatedbyVisualStudio.NETWebApplications

containscommentsspecifictothemostcommonlyusedsettings.These

commentsprovideguidanceforusingtheavailableparametersfora

givenconfigurationelement(althoughnotallconfigurationelements

appearinthedefaultWeb.configfile).Completedocumentationis

providedintheVisualBasic.NEThelpfilesinstalledbydefaultwith

VisualStudio.NET.

InadditiontothecommentsfoundintheWeb.configfilegeneratedby

VisualStudio.NET,themachine.configfilecontainscommentswith

specificsettingsforcertainelements.Thesecommentscanguideyou

whenyoumakeconfigurationchanges.AppendixBdescribesthe

availableASP.NETconfigurationelementsandtheirsettings.

ToillustratehowtoconfigureASP.NETapplications,letslookattwo

examples.Thefirstexampleshowshowtousethe

elementtodefineacustompagetohandle404-NotFounderrorswhena

userrequestsapagethatdoesntexistinyourapplication.Thesecond

exampleshowshowtousetheelementtoremovethe

SessionStateModuleforapplicationsthatdonotusesessionstate.



Configureacustom404handler

1. CreateanewprojectnamedChapter_05ifyoudidntdosoin

thepreviousexercise.

2. AddanewWebFormtotheproject.Namethefilefnf.aspx.

ThenewWebFormwillbedisplayedinDesignview,asshown

intheillustrationonthefollowingpage.



3. AddaLabelcontroltothepage,asshowninthefollowing

illustration.



4. Double-clicktheWebFormintheDesignviewwindow.

Thecode-behindmoduleforfnf.aspxwillbedisplayedinthe

codeeditorwindow,withthecursorautomaticallymovedtothe

Page_Loadeventhandler.Notethatalocaldeclaration

(highlightedinthefollowingillustration)hasbeenaddedtothe

code-behindfortheLabelcontroltoallowprogrammaticaccess

tothecontrolbyitsname,Label1:

protectedSystem.Web.UI.WebControls.LabelLabel1;



5. ReplacetheplaceholdercommentinthePage_Loadevent

handlerwiththecodeintheillustrationonthefollowingpage.

(TheASP.NETruntimeaddstheaspxerrorpathquerystring

variableautomaticallyandpopulatesitwiththepathrequested

bytheuserwhenredirectingfromanHTTPerror.)

Label1.Text="We'resorry.Thepageyourequested:"R



6. Savefnf.aspxandfnf.aspx.vb.

7. Ifitisnotalreadyopen,openWeb.configbydouble-clickingitin

SolutionExplorer.

8. Modifytheelementtolooklikethecodeinthe

illustrationonthefollowingpage,andthensavethefile.(The



childelementmapstheHTTP404errorcodetoredirect

totheWebFormcreatedinapreviousstep.)






9. FromtheBuildmenu,selectBuildChapter_05tobuildthe

project.

10. Right-clickWebForm1.aspx(thedefaultWebFormaddedtothe

projectwhenitwascreated),selectBrowseWith,thenselect

MicrosoftInternetExplorerfromtheBrowserListwindow,and

thenclickBrowse,asshowninthefollowingillustration.(This

willopenthepageinaseparatebrowserwindow,ratherthan

oneembeddedintheIDE.)



11. UsingtheInternetExploreraddressbar,changethefileportion

oftheURLfromWebForm1.aspxtoWebForm.aspx(afilethat

doesnotexist),andthenclicktheGobutton.



Thepagewillredirecttofnf.aspx,anddisplayamessagesimilar

tothefollowing.(Thepathcanvarydependingonhowyouset

upyourproject.)



Youcanusethistechniquetoprovideusefulerrormessagestoyour

users,asinthisexample,oryoucanexpandonitbyusingtheredirect

pagetosendanotificationtoanadministratoroftheerror,usingthe

Microsoft.NETFrameworksSmtpMailclass.(Youlllearnhowtousethe

SmtpMailclassinChapter8.)

HttpModulesareclassesthatparticipateintheprocessingofevery

requestmadetoanapplication.Thebuilt-inHttpModulesinASP.NET

includeSessionStateModuleandOutputCacheModule,aswellas

modulesforeachofthebuilt-inauthenticationmethodsinASP.NET.

Thesemodulesareaddedbydefaultinmachine.configusingthe

element.Youcanusetheelementinyour

Web.configfiletoremoveanyofthesemodulesthatyourenotusing,or

toaddadditionalhttpModules(includingyourowncustomhttpModules).



RemoveanHttpModule

1. OpenWeb.config(ifitisntalreadyopen)bydouble-clickingitin

SolutionExplorer.



2. Justunderthetag,addan

elementtothefile,asshownintheillustrationonthefollowing

page:





Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5: Configuring an ASP.NET Application

Tải bản đầy đủ ngay(0 tr)

×