Tải bản đầy đủ - 0 (trang)
Chapter 7: ASP.NET and Web Forms

Chapter 7: ASP.NET and Web Forms

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

Overview

MicrosoftASP.NETisaplatformfordevelopingWebapplications,andit's

anambitiouspartoftheMicrosoft.NETFramework.ASP.NETallowsyou

towriteXMLWebservices(asdescribedinChapter12)anddeveloprich

Websites(asdiscussedinthischapter).ASP.NETWebpagesusean

event-basedcontrolmodel,whichmakeswritingthemremarkablysimilar

tocraftingordinarystand-aloneMicrosoftWindows–basedapplications.

However,thissimilaritycanbedeceiving.AsmostASP.NETdevelopers

willattest,Webapplicationshavetheirownidiosyncrasies.Forexample,

you'llneedtotakeextrastepstomaintainstate,transferinformation

betweenpages,handleclient-sideevents,performauthentication,and

ensureoptimalperformancewhenusingadatabase.Thischapter

considersalltheseissues.

Note Thischapterwon'tintroduceyoutoASP.NETifyou'venever

programmedwithitbefore.Instead,itwillhelpintermediate

ASP.NETdeveloperssolvecommonproblems.Foragood

introductiontoASP.NETbasics,consultoneofthemany

dedicatedbooksandrefertotheMicrosoftASP.NETWebsite

(http://www.asp.net).

Therecipesyou'llfindinthischaptercoverthefollowingtopics:

Howtoredirectuserrequests(recipe7.1).

Differentwaystomaintainstatebetweenpagerequests(recipes

7.2and7.3).

Waystoenhanceyourinterfacewithclient-sidefeaturesusing

JavaScript(recipes7.4,7.5,and7.6).

Waystoallowuserstouploadfiles(recipe7.7).

Twoapproachesforauthenticatingtheclient:integratedWindows

authenticationwithInternetInformationServices(IIS)(recipe7.8)

andcustomform-basedauthentication(recipe7.9).



HowtovalidateuserinputwithoutusingASP.NETvalidation

controls(recipe7.10).

ApproachesfordynamicallygeneratingWebcontrols(recipe

7.11),graphics(recipe7.12),andusercontrols(recipe7.13).

Techniquesforimprovingperformancewithoutputcaching

(recipe7.14)anddatacaching(recipe7.15).

Troubleshootingsuggestionstosolvetheinfamous"unableto

startdebuggingontheserver"errormessage(recipe7.16).

HowtochangetheWindowsaccountcontextinwhichan

ASP.NETapplicationruns(recipe7.17).

ThischapterusesthebasicWebclassesintheSystem.Webnamespace

andtheWebcontrolclassesintheSystem.Web.UI.WebControls

namespace.Whenusingclassesinthesecorenamespaces,thefully

qualifiedclassnameusuallywon'tbeindicated.

Note Everyrecipeinthischapteriscontainedinaseparatevirtual

directory.Tocreatetherequiredvirtualdirectories,refertothe

readme.txtincludedwiththesamplecodethataccompanies

thebook.Alternatively,youcanaddtheWebpagefiles(both

the.asmxpagesandthe.cscode-behindfiles)toanexisting

Webprojectonyourcomputertousethem.



7.1RedirecttheUsertoAnotherPage

Problem

YouneedtotransferexecutionfromoneASP.NETWebpagetoanother,

oryouwanttoredirecttheusertoacompletelydifferentsite.



Solution

UsetheHttpResponse.Redirectmethodtoredirecttheusertoanew

URL,orusetheHttpServerUtility.Transfermethodforafasterwayto

transfertheusertoanotherASP.NETWebformonthesameserver.



Discussion



TheeasiestwaytoredirectauserfromoneWebpagetoanotheristo

usetheHttpResponse.RedirectmethodandsupplyanewURL.Youcan

accessthecurrentHttpResponseobjectthroughtheHttpContextobject

orbyusingtheReponsepropertyofaPageoraControlobject.Here's

anexampleofaneventhandlerthatredirectstheuserinresponsetoa

buttonclick:

privatevoidcmdRedirect_Click(objectsender,System.EventArgs

Response.Redirect("newpage.aspx");

}

TheRedirectmethodworkswithrelativeURLstoresourcesinthesame

virtualdirectory,andwithfullyqualifiedURLs.URLscanpointtoother

ASP.NETpages,othertypesofdocuments(suchasHTMLpagesor

images),andotherWebservers.

TheRedirectmethodsendsaredirectinstructiontothebrowser.The

browserthenrequeststhenewpage.Theresultisthatthebrowserhas

tomaketworoundtripstotheWebserver,andtheWebserverhasto

handleanextrarequest.Amoreefficientoptionisavailablethroughthe

HttpServerUtility.Transfermethod,whichtransfersexecutiontoadifferent

ASP.NETpageonthesameWebserver.Here'sanexample:



privatevoidcmdRedirect_Click(objectsender,System.EventArgs

Server.Transfer("newpage.aspx");

}

TheTransfermethoddoesn'trequireanextratriptotheclient,butitwon't

workifyouneedtotransferexecutiontoanotherserveroranothertype

ofresourceotherthanaWebform(includingaclassicASPpage).



7.2StoreInformationBetweenRequests

Problem

Youneedtostoresomeuser-specificinformationbetweenpage

postbacks.



Solution

Useviewstate,querystringarguments,sessionstate,oracookie,

dependingonyourneeds.



Discussion

ASP.NETisastatelessprogrammingmodel.Everytimeapostbackis

triggered,yourcodeloadsintomemory,executes,andisreleasedfrom

memory.Ifyouwanttokeeptrackofinformationafteryourcodehas

finishedprocessing,youmustusesomeformofstatemanagement.

ASP.NETprovidesseveralwaystostoreinformation,orstate,between

requests.Thetypeofstateyouusedetermineshowlongtheinformation

willlive,whereitwillbestored,andhowsecureitwillbe.Table7.1lists

thevariousstateoptionsprovidedbyASP.NET.Thistabledoesn'tinclude

theCacheobject,whichprovidestemporarystorageandisdescribedin

recipe7.15.Youcanalsouseother,custom,approaches,suchashidden

fieldsoraback-enddatabase.

Table7.1:TypesofStateManagement

Typeof

State



Allowed

Data



Storage

Location



All

Ahidden

ViewState serializable fieldinthe



Lifetime



Security



Bydefault,it's

insecure.

However,you

canusepage

Lostwhenthe

directivesto

usernavigatesto enforce



.NETdata currentWeb anotherpage.

types.

page.



encryption

andhashing

toprevent

data

tampering.



Query

String



Lostwhenthe

userentersanew Clearlyvisible

The

Stringdata

URLorclosesthe andeasyfor

browser's

only.

browser.However, theuserto

URLstring.

itcanbestoredin modify.

abookmark.



Session

State



Server

memory

(can

All

optionally

serializable be

.NETdata configured

types.

foran

external

processor

database).



Timesoutaftera

predefinedperiod Secure

(usually20

becausedata

minutes,butthis isnever

periodcanbe

transmittedto

alteredgloballyor theclient.

programmatically).



Custom

Cookies



Theclient's

computer

(inmemory

orasmall

Stringdata

textfile,

only.

depending

onits

lifetime

settings).



Setbythe

programmer.Can

beusedin

multiplepages

andcanpersist

betweenvisits.



All

Application serializable Server

State

.NETdata memory.



Insecure,and

itcanbe

modifiedby

theuser.



Thelifetimeofthe

application

(typically,untilthe Secure

becausedata

serveris

rebooted).Unlike isnever



types.



othermethods,

transmittedto

applicationdatais theclient.

globaltoallusers.



Thesyntaxfordifferentdata-storingmethodsissimilar.Dataisstoredin

acollectionobjectandindexedusingastringname.

Figure7.1showsaWebpagethatperformsatestofseveraldifferent

formsofsessionstate.WhentheuserclickstheStoreDatabutton,anew

System.DateTimeobjectiscreatedandstoredinpageviewstate,

sessionstate,andacustomcookie.WhentheuserclickstheGetData

button,thisinformationisretrievedanddisplayed.Finally,theClearData

buttonremovesinformationfromalltypesofstate.





Figure7.1:Testingdifferentstatemanagement

approaches.

Here'sthepagecode:

usingSystem;

usingSystem.Web;

usingSystem.Web.UI.WebControls;

usingSystem.Web.SessionState;

publicclassTestState:System.Web.UI.Page{

protectedSystem.Web.UI.WebControls.ButtoncmdClear;



protectedSystem.Web.UI.WebControls.ButtoncmdStore;

protectedSystem.Web.UI.WebControls.ButtoncmdGetData;

protectedSystem.Web.UI.WebControls.LabellblData;

//(Designercodeomitted.)



privatevoidcmdStore_Click(objectsender,System.EventArgs

//Createatestobject.

DateTimenow=DateTime.Now;

//Storetheobjectinviewstate.

ViewState["TestData"]=now;

//Storetheobjectinsessionstate.

Session["TestData"]=now;



//Storetheobjectinacookie.

//Checkifthecookiealreadyexists(namedRecipe07-0

if(Request.Cookies["Recipe07-02"]==null){

//Createthecookie.

HttpCookiecookie=newHttpCookie("Recipe07-02");



//Thecookiecanonlystorestringdata.

//Itcanstoremultiplevalues,eachwithadiffer

cookie["TestData"]=now.ToString();



//(YoucanmodifyadditionalCookiepropertiesto

//theexpirydate.)



//Attachthecookietotheresponse.

//Itwillbesubmittedwithallfuturerequeststo

//untilitexpires.

Response.Cookies.Add(cookie);

}

}



privatevoidcmdGetData_Click(objectsender,System.EventAr

lblData.Text="";

//Checkforinformationinviewstate.

if(ViewState["TestData"]!=null){

DateTimedata=(DateTime)ViewState["TestData"];

lblData.Text+="Viewstatedata:"+

data.ToString()+"
";

}else{

lblData.Text+="Noviewstatedatafound.
";

}



//Checkforinformationinsessionstate.

if(Session["TestData"]!=null){

DateTimedata=(DateTime)Session["TestData"];

lblData.Text+="Sessionstatedata:"+

data.ToString()+"
";

}else{

lblData.Text+="Nosessiondatafound.
";

}

//Checkforinformationinacustomcookie.

HttpCookiecookie=Request.Cookies["Recipe07-02"];

if(cookie!=null){

stringcookieData=(string)cookie["TestData"];

lblData.Text+="Cookiedata:"+

cookieData+"
";



}else{

lblData.Text+="Nocookiedatafound.
";

}

}



privatevoidcmdClear_Click(objectsender,System.EventArgs



ViewState["TestData"]=null;

Session["TestData"]=null;

//(YoucanalsouseSession.Abandontoclearallsessi

//information.)



//Toclearacookieyoumustreplaceitwith

//acookiethathasanexpirationdatethathasalread

HttpCookiecookie=newHttpCookie("Recipe07-02");

cookie.Expires=DateTime.Now.AddDays(-1);

Response.Cookies.Add(cookie);

}

}

Onetypeofstatethatthispagedoesn'tdemonstrateisthequerystring.

Thequerystringrequiresapageredirectandisidealfortransferring

informationfromonepagetoanother.Tosetinformation,youmust

redirecttheusertoanewpageandaddthequerystringargumentsto

theendoftheURL.YoucanusetheHttpServerUtility.UrlEncodeand

UrlDecodemethodstoensurethestringdataisURLlegal.Thismethod

properlyescapesanyspecialcharacters.

DateTimenow=DateTime.Now;

stringdata=Server.UrlEncode(now.ToString());

Response.Redirect("newPage.aspx?TestData="+data);

Toretrievethisinformation,youcanusetheHttpResponse.QueryString

collection:

//Checkforinformationinthequerystring.

if(Request.QueryString["TestData"]!=null){



stringdata=Request.QueryString["TestData"];

data=Server.UrlDecode(data);

lblData.Text+="Foundquerystringdata:"+data+

}



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

Chapter 7: ASP.NET and Web Forms

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

×