50857887-asp-net

download 50857887-asp-net

of 91

Transcript of 50857887-asp-net

  • 7/29/2019 50857887-asp-net

    1/91

    Understanding ASP.NET View State

    Scott Mitchell4GuysFromRolla.com

    May 2004

    Applies to:Microsoft ASP.NETMicrosoft Visual Studio .NET

    Summary: Scott Mitchell looks at the benefits of and confusion around View State inMicrosoft ASP.NET. In addition, he shows you how you can interpret (and protect) the

    data stored in View State. (25 printed pages)

    Clickhere to download the code sample for this article.

    Contents

    IntroductionThe ASP.NET Page Life CycleThe Role of View StateView State and Dynamically Added ControlsThe ViewState Property

    Timing the Tracking of View StateStoring Information in the Page's ViewState PropertyThe Cost of View StateDisabling the View StateSpecifying Where to Persist the View StateParsing the View StateView State and Security ImplicationsConclusion

    Introduction

    Microsoft ASP.NET view state, in a nutshell, is the technique used by an ASP.NETWeb page to persist changes to the state of a Web Form across postbacks. In myexperiences as a trainer and consultant, view state has caused the most confusion amongASP.NET developers. When creating custom server controls or doing more advancedpage techniques, not having a solid grasp of what view state is and how it works cancome back to bite you. Web designers who are focused on creating low-bandwidth,streamlined pages oftentimes find themselves frustrated with view state, as well. The

    view state of a page is, by default, placed in a hidden form field named __VIEWSTATE.

  • 7/29/2019 50857887-asp-net

    2/91

    This hidden form field can easily get very large, on the order of tens of kilobytes. Not

    only does the __VIEWSTATE form field cause slower downloads, but, whenever the userposts back the Web page, the contents of this hidden form field must be posted back inthe HTTP request, thereby lengthening the request time, as well.

    This article aims to be an in-depth examination of the ASP.NET view state. We'll look atexactly what view state is storing, and how the view state is serialized to the hidden formfield and deserialized back on postback. We'll also discuss techniques for reducing thebandwidth required by the view state.

    Note This article is geared toward the ASP.NET page developer rather than theASP.NET server control developer. This article therefore does not include a discussionon how a control developer would implement saving state. For an in-depth discussion onthat issue, refer to the bookDeveloping Microsoft ASP.NET Server Controls andComponents.

    Before we can dive into our examination of view state, it is important that we first take aquick moment to discuss the ASP.NET page life cycle. That is, what exactly happenswhen a request comes in from a browser for an ASP.NET Web page? We'll step throughthis process in the next section.

    The ASP.NET Page Life Cycle

    Each time a request arrives at a Web server for an ASP.NET Web page, the first thing theWeb server does is hand off the request to the ASP.NET engine. The ASP.NET enginethen takes the request through a pipeline composed of numerous stages, which includesverifying file access rights for the ASP.NET Web page, resurrecting the user's session

    state, and so on. At the end of the pipeline, a class corresponding to the requestedASP.NET Web page is instantiated and the ProcessRequest() method is invoked (seeFigure 1).

    Figure 1. ASP.NET Page Handling

  • 7/29/2019 50857887-asp-net

    3/91

    This life cycle of the ASP.NET page starts with a call to the ProcessRequest() method.This method begins by initializing the page's control hierarchy. Next, the page and itsserver controls proceed lock-step through various phases that are essential to executing an

    ASP.NET Web page. These steps include managing view state, handling postback events,and rendering the page's HTML markup. Figure 2 provides a graphical representation ofthe ASP.NET page life cycle. The life cycle ends by handing off the Web page's HTMLmarkup to the Web server, which sends it back to the client that requested the page.

    Note A detailed discussion of the steps leading up to the ASP.NET page life cycle isbeyond the scope of this article. For more information read Michele Leroux-Bustamante'sInside IIS & ASP.NET. For a more detailed look at HTTP handlers, which are theendpoints of the ASP.NET pipeline, check out my previous article on HTTP Handlers.

    What is important to realize is that each and every time an ASP.NET Web page is

    requested it goes through these same life cycle stages (shown in Figure 2).

    Figure 2. Events in the Page Life Cycle

    Stage 0 - Instantiation

    The life cycle of the ASP.NET page begins with instantiation of the class that representsthe requested ASP.NET Web page, but how is this class created? Where is it stored?

  • 7/29/2019 50857887-asp-net

    4/91

    ASP.NET Web pages, as you know, are made up of both an HTML portion and a codeportion, with the HTML portion containing HTML markup and Web control syntax. TheASP.NET engine converts the HTML portion from its free-form text representation into aseries of programmatically-created Web controls.

    When an ASP.NET Web page is visited for the first time after a change has been made tothe HTML markup or Web control syntax in the .aspx page, the ASP.NET engine auto-generates a class. If you created your ASP.NET Web page using the code-behindtechnique, this autogenerated class is derived from the page's associated code-behindclass (note that the code-behind class must be derived itself, either directly or indirectly,

    from the System.Web.UI.Page class); if you created your page with an in-line, server-

    side block, the class derives directly from System.Web.UI.Page. In eithercase, this autogenerated class, along with a compiled instance of the class, is stored in the

    WINDOWS\Microsoft.NET\Framework\version\Temporary ASP.NET Files folder, in

    part so that it doesn't need to be recreated for each page request.

    The purpose of this autogenerated class is to programmatically create the page's controlhierarchy. That is, the class is responsible for programmatically creating the Webcontrols specified in the page's HTML portion. This is done by translating the Web

    control syntaxinto the class'sprogramming language (C# or Microsoft Visual Basic .NET, most typically). Inaddition to the Web control syntax being converted into the appropriate code, the HTMLmarkup present in the ASP.NET Web page's HTML portion is translated to Literalcontrols.

    All ASP.NET server controls can have a parent control, along with a variable number of

    child controls. The System.Web.UI.Page class is derived from the base control class

    (System.Web.UI.Control), and therefore also can have a set of child controls. The top-level controls declared in an ASP.NET Web page's HTML portion are the direct children

    of the autogenerated Page class. Web controls can also be nested inside one another. Forexample, most ASP.NET Web pages contain a single server-side Web Form, withmultiple Web controls inside the Web Form. The Web Form is an HTML control

    (System.Web.UI.HtmlControls.HtmlForm). Those Web controls inside the Web Formare children of the Web Form.

    Since server controls can have children, and each of their children may have children, andso on, a control and its descendents form a tree of controls. This tree of controls is calledthe control hierarchy. The root of the control hierarchy for an ASP.NET Web page is the

    Page-derived class that is autogenerated by the ASP.NET engine.

    Whew! Those last few paragraphs may have been a bit confusing, as this is not the easiestsubject to discuss or digest. To clear out any potential confusion, let's look at a quickexample. Imagine you have an ASP.NET Web page with the following HTML portion:

    Copy

  • 7/29/2019 50857887-asp-net

    5/91

    Welcometomy Homepage!Whatis yourname?
    Whatis yourgender?MaleFemaleUndecided


    When this page is first visited, a class will be autogenerated that contains code to

    programmatically build up the control hierarchy. The control hierarchy for this examplecan be seen in Figure 3.

    Figure 3. Control Hierarchy for sample page

    This control hierarchy is then converted to code that is similar to the following:

    CopyPage.Controls.Add(

    newLiteralControl(@"\r\n\r\nWelcometomy Homepage!\r\n"));

    HtmlFormForm1=newHtmlForm();Form1.ID ="Form1";Form1.Method="post";Form1.Controls.Add(newLiteralControl("\r\nWhatis yourname?\r\n"));

    TextBox TextBox1=new TextBox();TextBox1.ID ="txtName";

  • 7/29/2019 50857887-asp-net

    6/91

    Form1.Controls.Add(TextBox1);Form1.Controls.Add(newLiteralControl("\r\n
    Whatis yourgender?\r\n"));

    DropDownList DropDownList1=new DropDownList();DropDownList1.ID ="ddlGender";ListItemListItem1=newListItem();ListItem1.Selected=true;ListItem1.Value="M";ListItem1.Text="Male";DropDownList1.Items.Add(ListItem1);ListItemListItem2=newListItem();ListItem2.Value="F";ListItem2.Text="Female";DropDownList1.Items.Add(ListItem2);ListItemListItem3=newListItem();ListItem3.Value="U";ListItem3.Text="Undecided";DropDownList1.Items.Add(ListItem3);Form1.Controls.Add(newLiteralControl("\r\n
    \r\n"));

    ButtonButton1=newButton();Button1.Text="Submit!";Form1.Controls.Add(Button1);Form1.Controls.Add(newLiteralControl("\r\n\r\n"));

    Controls.Add(Form1);

    Note The C# source code above is not the precise code that is autogenerated by theASP.NET engine. Rather, it's a cleaner and easier to read version of the autogeneratedcode. To see the full autogenerated codewhich won't win any points for readabilitynavigate to the

    WINDOWS\Microsoft.NET\Framework\Version\Temporary ASP.NET Files

    folder and open one of the.csor.vbfiles.

    One thing to notice is that, when the control hierarchy is constructed, the properties thatare explicitly set in the declarative syntax of the Web control are assigned in the code.(For example, the Button Web control has its Text property set to "Submit!" in the

    declarative syntax Text="Submit!" as well as in the autogenerated class

    Button1.Text="Submit!";.

    Stage 1 - Initialization

    After the control hierarchy has been built, the Page, along with all of the controls in its

    control hierarchy, enter the initialization stage. This stage is marked by having the Page

    and controls fire theirInit events. At this point in the page life cycle, the controlhierarchy has been constructed, and the Web control properties that are specified in thedeclarative syntax have been assigned.

  • 7/29/2019 50857887-asp-net

    7/91

    We'll look at the initialization stage in more detail later in this article. With regards toview state it is important for two reasons; first, server controls don't begin tracking viewstate changes until right at the end of the initialization stage. Second, when addingdynamic controls that need to utilize view state, these controls will need to be added

    during the Page's Init event as opposed to the Load event, as we'll see shortly.

    Stage 2 - Load View State

    The load view state stage only happens when the page has been posted back. During thisstage, the view state data that had been saved from the previous page visit is loaded and

    recursively populated into the control hierarchyof the Page. It is during this stage thatthe view state is validated. As we'll discuss later in this article, the view state can becomeinvalid due to a number of reasons, such as view state tampering, and injecting dynamiccontrols into the middle of the control hierarchy.

    Stage 3 - Load Postback Data

    The load postback data stage also only happens when the page has been posted back. Aserver control can indicate that it is interested in examining the posted back data by

    implementing the IPostBackDataHandler interface. In this stage in the page life cycle,the Page class enumerates the posted back form fields, and searches for the correspondingserver control. If it finds the control, it checks to see if the control implements the

    IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to

    the server control by calling the control's LoadPostData() method. The server controlwould then update its state based on this postback data.

    To help clarify things, let's look at a simple example. One nice thing about ASP.NET is

    that the Web controls in a Web Form remember their values across postback. That is, ifyou have a TextBox Web control on a page and the user enters some value into the

    TextBox and posts back the page, the TextBox's Text property is automatically updatedto the user's entered value. This happens because the TextBox Web control implements

    the IPostBackDataHandler interface, and the Page class hands off the appropriate value

    to the TextBox class, which then updates its Text property.

    To concretize things, imagine that we have an ASP.NET Web page with a TextBox

    whose ID property is set to txtName. When the page is first visited, the following HTML

    will be rendered for the TextBox: . When the user enters a value into this TextBox (such as, "Hello,

    World!") and submits the form, the browser will make a request to the same ASP.NETWeb page, passing the form field values back in the HTTP POST headers. These include

    the hidden form field values (such as __VIEWSTATE), along with the value from the

    txtName TextBox.

    When the ASP.NET Web page is posted back in the load postback data stage, the Pageclass sees that one of the posted back form fields corresponds to the

    IPostBackDataHandler interface. There is such a control in the hierarchy, so the

  • 7/29/2019 50857887-asp-net

    8/91

    TextBox's LoadPostData() method is invoked, passing in the value the user entered into

    the TextBox ("Hello, World!"). The TextBox's LoadPostData() method simply assigns

    this passed in value to its Text property.

    Notice that in our discussion on the load postback data stage, there was no mention of

    view state. You might naturally be wondering, therefore, why I bothered to mention theload postback data stage in an article about view state. The reason is to note the absenceof view state in this stage. It is a common misconception among developers that viewstate is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, andother Web controls remember their values across postback. This is not the case, as thevalues are identified via posted back form field values, and assigned in the

    LoadPostData() method for those controls that implement IPostBackDataHandler.

    Stage 4 - Load

    This is the stage with which all ASP.NET developers are familiar, as we've all created an

    event handler for a page's Load event (Page_Load). When the Load event fires, the viewstate has been loaded (from stage 2, Load View State), along with the postback data

    (from stage 3, Load Postback Data). If the page has been posted back, when the Loadevent fires we know that the page has been restored to its state from the previous pagevisit.

    Stage 5 - Raise Postback Event

    Certain server controls raise events with respect to changes that occurred between

    postbacks. For example, the DropDownList Web control has a SelectedIndexChanged

    event, which fires if the DropDownList's SelectedIndex has changed from the

    SelectedIndex value in the previous page load. Another example: if the Web Form wasposted back due to a Button Web control being clicked, the Button's Click event is firedduring this stage.

    There are two flavors of postback events. The first is a changedevent. This event fireswhen some piece of data is changed between postbacks. An example is the

    DropDownLists SelectedIndexChanged event, or the TextBox's TextChanged event.

    Server controls that provide changed events must implement the IPostBackDataHandlerinterface. The other flavor of postback events is the raisedevent. These are events thatare raised by the server control for whatever reason the control sees fit. For example, the

    Button Web control raises the Click event when it is clicked, and the Calendar control

    raises the VisibleMonthChanged event when the user moves to another month. Controlsthat fire raised events must implement the IPostBackEventHandler interface.

    Since this stage inspects postback data to determine if any events need to be raised, thestage only occurs when the page has been posted back. As with the load postback datastage, the raise postback event stage does not use view state information at all. Whetheror not an event is raised depends on the data posted back in the form fields.

  • 7/29/2019 50857887-asp-net

    9/91

    Stage 6 - Save View State

    In the save view state stage, the Page class constructs the page's view state, whichrepresents the state that must persist across postbacks. The page accomplishes this by

    recursively calling the SaveViewState() method of the controls in its control hierarchy.

    This combined, saved state is then serialized into a base-64 encoded string. In stage 7,when the page's Web Form is rendered, the view state is persisted in the page as a hiddenform field.

    Stage 7 - Render

    In the render stage the HTML that is emitted to the client requesting the page is

    generated. The Page class accomplishes this by recursively invoking the

    RenderControl() method of each of the controls in its hierarchy.

    These seven stages are the most important stages with respect to understanding view

    state. (Note that I did omit a couple of stages, such as the PreRender and Unload stages.)As you continue through the article, keep in mind that every single time an ASP.NETWeb page is requested, it proceeds through these series of stages.

    The Role of View State

    View state's purpose in life is simple: it's there to persist state across postbacks. (For anASP.NET Web page, its state is the property values of the controls that make up itscontrol hierarchy.) This begs the question, "What sort of state needs to be persisted?" Toanswer that question, let's start by looking at what state doesn'tneed to be persistedacross postbacks. Recall that in the instantiation stage of the page life cycle, the controlhierarchy is created and those properties that are specified in the declarative syntax areassigned. Since these declarative properties are automatically reassigned on eachpostback when the control hierarchy is constructed, there's no need to store these propertyvalues in the view state.

    For example, imagine we have a Label Web control in the HTML portion with thefollowing declarative syntax:

    Copy

    When the control hierarchy is built in the instantiation stage, the Label's Text property

    will be set to "Hello, World!" and its Font property will have its Name property set toVerdana. Since these properties will be set each and every page visit during theinstantiation stage, there's no need to persist this information in the view state.

  • 7/29/2019 50857887-asp-net

    10/91

    What needs to be stored in the view state is any programmatic changes to the page's state.For example, suppose that in addition to this Label Web control, the page also containedtwo Button Web controls, a Change Message Button and an Empty Postback button. The

    Change Message Button has a Click event handler that assigns the Label's Text propertyto "Goodbye, Everyone!"; the Empty Postback Button just causes a postback, but doesn't

    execute any code. The change to the Label's Text property in the Change MessageButton would need to be saved in the view state. To see how and when this change wouldbe made, let's walk through a quick example. Assuming that the HTML portion of thepage contains the following markup:

    Copy



    And the code-behind class contains the following event handler for the Button's Clickevent:

    CopyprivatevoidbtnSubmit_Click(objectsender, EventArgse){lblMessage.Text="Goodbye, Everyone!";

    }

    Figure 4 illustrates the sequence of events that transpire, highlighting why the change tothe Label's Text property needs to be stored in the view state.

  • 7/29/2019 50857887-asp-net

    11/91

    Figure 4. Events and View State

    To understand why saving the Label's changed Text property in the view state is vital,consider what would happen if this information were not persisted in view state. That is,imagine that in step 2's save view state stage, no view state information was persisted. Ifthis were the case, then in step 3 the Label's Text property would be assigned to "Hello,World!" in the instantiation stage, but would not be reassigned to "Goodbye, Everyone!"

    in the load view state stage. Therefore, from the end user's perspective, the Label's Text

  • 7/29/2019 50857887-asp-net

    12/91

    property would be "Goodbye, Everyone!" in step 2, but would seemingly be reset to itsoriginal value ("Hello, World!") in step 3, after clicking the Empty Postback button.

    View State and Dynamically Added Controls

    Since all ASP.NET server controls contain a collection of child controls exposed throughthe Controls property, controls can be dynamically added to the control hierarchy by

    appending new controls to a server control's Controls collection. A thorough discussionof dynamic controls is a bit beyond the scope of this article, so we won't cover that topicin detail here; instead, we'll focus on how to manage view state for controls that areadded dynamically. (For a more detailed lesson on using dynamic controls, check outDynamic Controls in ASP.NET and Working with Dynamically Created Controls.)

    Recall that in the page life cycle, the control hierarchy is created and the declarativeproperties are set in the instantiation stage. Later, in the load view state stage, the statethat had been altered in the prior page visit is restored. Thinking a bit about this, three

    things become clear when working with dynamic controls:

    1. Since the view state only persists changed control state across postbacks, and notthe actual controls themselves, dynamically added controls must be added to theASP.NET Web page, on both the initial visit as well as all subsequent postbacks.

    2. Dynamic controls are added to the control hierarchy in the code-behind class, andtherefore are added at some point afterthe instantiation stage.

    3. The view state for these dynamically added controls is automatically saved in thesave view state stage. (What happens on postback if the dynamic controls havenot yet been added by the time the load view state stage rolls, however?)

    So, dynamically added controls must be programmatically added to the Web page oneach and every page visit. The best time to add these controls is during the initializationstage of the page life cycle, which occurs before the load view state stage. That is, wewant to have the control hierarchy complete before the load view state stage arrives. For

    this reason, it is best to create an event handler for the Page class's Init event in yourcode-behind class, and add your dynamic controls there.

    Note You may be able to get away with loading your controls in thePage_Loadevent handler and maintaining the view state properly. It all depends on whether or notyou are setting any properties of the dynamically loaded controls programmatically and,

    if so, when you're doing it relative to theControls.Add(dynamicControl)line. A thorough discussion of this is a bit beyond the scope of this article, but the reasonit may work is because theControlsproperty'sAdd()

  • 7/29/2019 50857887-asp-net

    13/91

    method recursively loads the parent's view state into its children, even though the loadview state stage has passed.

    When adding a dynamic control c to some parent controlp based on some condition (thatis, when not loading them on each and every page visit), you need to make sure that you

    add c to the end ofp's Controls collection. The reason is because the view state forpcontains the view state forp's children as well, and, as we'll discuss in the "Parsing theView State" section,p's view state specifies the view state for its children by index.(Figure 5 illustrates how inserting a dynamic control somewhere other than the end of theControls collection can cause a corrupted view state.)

    Figure 5. Effect of inserting controls on View State

    The ViewState Property

    Each control is responsible for storing its own state, which is accomplished by adding its

    changed state to its ViewState property. The ViewState property is defined in the

    System.Web.UI.Control class, meaning that all ASP.NET server controls have thisproperty available. (When talking about view state in general I'll use lower case letters

    with a space between view and state; when discussing the ViewState property, I'll usethe correct casing and code-formatted text.)

    If you examine the simple properties of any ASP.NET server control you'll see that theproperties read and write directly to the view state. (You can view the decompiled sourcecode for a .NET assembly by using a tool like Reflector.) For example, consider the

    HyperLink Web control's NavigateUrl property. The code for this property looks likeso:

    CopypublicstringNavigateUrl

  • 7/29/2019 50857887-asp-net

    14/91

    {get{stringtext=(string) ViewState["NavigateUrl"];if(text!=null)

    returntext;else

    returnstring.Empty;}set{ViewState["NavigateUrl"]=value;

    }}

    As this code sample illustrates, whenever a control's property is read, the control's

    ViewState is consulted. If there is not an entry in the ViewState, then the default valuefor the property is returned. When the property is assigned, the assigned value is written

    directly to the ViewState.

    Note All Web controls use the above pattern for simple properties. Simple properties arethose that are scalar values, like strings, integers, Booleans, and so on. Complexproperties, such as the Label's Font property, which might be classes themselves, use adifferent approach. Consult the bookDeveloping Microsoft ASP.NET Server Controlsand Components for more information on state maintenance techniques for ASP.NETserver controls.

    The ViewState property is of type System.Web.UI.StateBag. The StateBag classprovides a means to store name and value pairs, using a

    System.Collections.Specialized.HybridDictionary behind the scenes. As theNavigateUrl property syntax illustrates, items can be added to and queried from the

    StateBag using the same syntax you could use to access items from a Hashtable.

    Timing the Tracking of View State

    Recall that earlier I said the view state only stores state that needs to be persisted acrosspostbacks. One bit of state that does not need to be persisted across postbacks is thecontrol's properties specified in the declarative syntax, since they are automaticallyreinstated in the page's instantiation stage. For example, if we have a HyperLink Web

    control on an ASP.NET Web page and declaratively set the NavigateUrl property tohttp://www.ScottOnWriting.NET then this information doesn't need to be stored in theview state.

    Seeing the HyperLink control's NavigateUrl property's code, however, it looks as if the

    control's ViewState is written to whenever the property value is set. In the instantiation

    stage, therefore, where we'd have something like HyperLink1.NavigateUrl=

  • 7/29/2019 50857887-asp-net

    15/91

    http://www.ScottOnWriting.NET;, it would only make sense that this informationwould be stored in the view state.

    Regardless of what might seem apparent, this is not the case. The reason is because the

    StateBag class only tracks changes to its members afterits TrackViewState() method

    has been invoked. That is, if you have a StateBag, any and all additions or modificationsthat are made before TrackViewState() is made will not be saved when the

    SaveViewState() method is invoked. The TrackViewState() method is called at theend of the initialization stage, which happens after the instantiation stage. Therefore, the

    initial property assignments in the instantiation stagewhile written to the ViewState in

    the properties' set accessorsare not persisted during the SaveViewState() method call

    in the save view state stage, because the TrackViewState() method has yet to beinvoked.

    Note The reason theStateBag

    has theTrackViewState()method is to keep the view state as trimmed down as possible. Again, we don't want tostore the initial property values in the view state, as they don't need to be persisted acrosspostbacks. Therefore, theTrackViewState()method allows the state management to begin after the instantiation and initializationstages.

    Storing Information in the Page's ViewState Property

    Since the Page class is derived from the System.Web.UI.Control class, it too has aViewState property. In fact, you can use this property to persist page-specific and user-specific information across postbacks. From an ASP.NET Web page's code-behind class,the syntax to use is simply:

    CopyViewState[keyName]=value

    There are a number of scenarios when being able to store information in the Page's

    ViewState is useful. The canonical example is in creating a pageable, sortable DataGrid(or a sortable, editable DataGrid), since the sort expression must be persisted across

    postbacks. That is, if the DataGrid's data is first sorted, and then paged, when binding thenext page of data to the DataGrid it is important that you get the next page of the datawhen it is sorted by the user's specified sort expression. The sort expression thereforeneeds to be persisted in some manner. There are assorted techniques, but the simplest, in

    my opinion, is to store the sort expression in the Page's ViewState.

    For more information on creating sortable, pageable DataGrids (or a pageable, sortable,editable DataGrid), pick up a copy of my bookASP.NET Data Web Controls Kick Start.

  • 7/29/2019 50857887-asp-net

    16/91

    The Cost of View State

    Nothing comes for free, and view state is no exception. The ASP.NET view state imposestwo performance hits whenever an ASP.NET Web page is requested:

    1. On all page visits, during the save view state stage the Page class gathers thecollective view state for all of the controls in its control hierarchy and serializesthe state to a base-64 encoded string. (This is the string that is emitted in the

    hidden __VIEWSTATE form filed.) Similarly, on postbacks, the load view statestage needs to deserialize the persisted view state data, and update the pertinentcontrols in the control hierarchy.

    2. The __VIEWSTATE hidden form field adds extra size to the Web page that theclient must download. For some view state-heavy pages, this can be tens ofkilobytes of data, which can require several extra seconds (or minutes!) for

    modem users to download. Also, when posting back, the __VIEWSTATE form fieldmust be sent back to the Web server in the HTTP POST headers, thereby

    increasing the postback request time.

    If you are designing a Web site that is commonly accessed by users coming over amodem connection, you should be particularly concerned with the bloat the view statemight add to a page. Fortunately, there are a number of techniques that can be employedto reduce view state size. We'll first see how to selectively indicate whether or not aserver control should save its view state. If a control's state does not need to be persistedacross postbacks, we can turn off view state tracking for that control, thereby saving theextra bytes that would otherwise have been added by that control. Following that, we'llexamine how to remove the view state from the page's hidden form fields altogether,storing the view state instead on the Web server's file system.

    Disabling the View State

    In the save view state stage of the ASP.NET page life cycle, the Page class recursivelyiterates through the controls in its control hierarchy, invoking each control's

    SaveViewState() method. This collective state is what is persisted to the hidden

    __VIEWSTATE form field. By default, all controls in the control hierarchy will record their

    view state when theirSaveViewState() method is invoked. As a page developer,however, you can specify that a control should not save its view state or the view state of

    its children controls by setting the control's EnableViewState property to False (the

    default is True).

    The EnableViewState property is defined in the System.Web.UI.Control class, so all

    server controls have this property, including the Page class. You can therefore indicate

    that an entire page's view state need not be saved by setting the Page class's

    EnableViewState to False. (This can be done either in the code-behind class with

    Page.EnableViewState=false; or as a @Page-level directive.)

  • 7/29/2019 50857887-asp-net

    17/91

    Not all Web controls record the same amount of information in their view state. TheLabel Web control, for example, records only programmatic changes to its properties,which won't greatly impact the size of the view state. The DataGrid, however, stores allof its contents in the view state. For a DataGrid with many columns and rows, the viewstate size can quickly add up! For example, the DataGrid shown in Figure 6 (and included

    in this article's code download as HeavyDataGrid.aspx) has a view state size of roughly2.8 kilobytes, and a total page size of 5,791 bytes. (Almost half of the page's size is due

    to the __VIEWSTATE hidden form field!) Figure 7 shows a screenshot of the view state,which can be seen by visiting the ASP.NET Web page, doing a View\Source, and then

    locating the __VIEWSTATE hidden form field.

  • 7/29/2019 50857887-asp-net

    18/91

    Figure 6. DataGrid control

  • 7/29/2019 50857887-asp-net

    19/91

    Figure 7. View State for DataGrid control

    The download for this article also includes an ASP.NET Web page called

    LightDataGrid.aspx, which has the same DataGrid as shown in Figure 6, but with the

    EnableViewState property set to False. The total view state size for this page? 96 bytes.

    The entire page size clocks in a 3,014 bytes. LightDataGrid.aspxboasts a view state

    size about 1/30th the size ofHeavyDataGrid.aspx, and a total download size that's about

    half ofHeavyDataGrid.aspx. With wider DataGrids with more rows, this difference

    would be even more pronounced. (For more information on performance comparisonsbetween view state-enabled DataGrids and view state-disabled DataGrids, refer toDeciding When to Use the DataGrid, DataList, or Repeater.)

    Hopefully the last paragraph convinces you of the benefit of intelligently setting the

    EnableViewState property to False, especially for "heavy" view state controls like the

    DataGrid. The question now, is, "When can I safely set the EnableViewState property toFalse?" To answer that question, consider when you need to use the view stateonlywhen you need to remember state across postbacks. The DataGrid stores its contentsin the view state so the page developer doesn't need to rebind the database data to theDataGrid on each and every page load, but only on the first one. The benefit is that the

    database doesn't need to be accessed as often. If, however, you set a DataGrid'sEnableViewState property to False, you'll need to rebind the database data to theDataGrid on both the first page load and every subsequent postback.

    For a Web page that has a read-only DataGrid, like the one in Figure 6, you'd definitely

    want to set the DataGrid's EnableViewState property to False. You can even createsortable and pageable DataGrids with the view state disabled (as can be witnessed in the

    LightDataGrid-WithFeatures.aspx page, included in the download), but, again, you'll

  • 7/29/2019 50857887-asp-net

    20/91

    need to be certain to bind the database data to the DataGrid on the first page visit, as wellas on all subsequent postbacks.

    Note Creating an editable DataGrid with disabled view state requires some intricateprogramming, which involves parsing of the posted back form fields in the editable

    DataGrid. Such strenuous effort is required because, with an editable DataGrid blindlyrebinding, the database data to the DataGrid will overwrite any changes the user made(see this FAQ for more information).

    Specifying Where to Persist the View State

    After the page has collected the view state information for all of the controls in its control

    hierarchy in the save view state stage, it persists it to the __VIEWSTATE hidden form field.This hidden form field can, of course, greatly add to the overall size of the Web page.

    The view state is serialized to the hidden form field in the Page class's

    SavePageStateToPersistenceMedium() method during the save view state stage, and

    is deserialized by the Page class's LoadPageStateFromPersistenceMedium() method inthe load view state stage. With just a bit of work we can have the view state persisted tothe Web server's file system, rather than as a hidden form field weighing down the page.

    To accomplish this we'll need to create a class that derives from the Page class and

    overrides the SavePageStateToPersistenceMedium() and

    LoadPageStateFromPersistenceMedium() methods.

    Note There is a third-party product called Flesk.ViewStateOptimizerthat reduces theview state bloat using a similar technique.

    The view state is serialized and deserialized by the System.Web.UI.LosFormatter

    classthe LOS stands for limited object serializationand is designed to efficientlyserialize certain types of objects into a base-64 encoded string. The LosFormatter can

    serialize any type of object that can be serialized by the BinaryFormatter class, but isbuilt to efficiently serialize objects of the following types:

    y Stringsy Integersy Booleansy Arrays

    y ArrayLists

    y Hashtables

    y Pairs

    y Triplets

    Note ThePairandTriplet

  • 7/29/2019 50857887-asp-net

    21/91

    are two classes found in theSystem.Web.UInamespace, and provide a single class to store either two or three objects. ThePairclass has properties

    FirstandSecondto access its two elements, whileTriplethasFirst,Second, andThird

    as properties.

    The SavePageStateToPersistenceMedium() method is called from the Page class andpassed in the combined view state of the page's control hierarchy. When overriding this

    method, we need to use the LosFormatter() to serialize the view state to a base-64encoded string, and then store this string in a file on the Web server's file system. Thereare two main challenges with this approach:

    1. Coming up with an acceptable file naming scheme. Since the view state for a pagewill likely vary based on the user's interactions with the page, the stored viewstate must be unique for each user and for each page.

    2. Removing the view state files from the file system when they are no longerneeded.

    To tackle the first challenge, we'll name the persisted view state file based on the user's

    SessionID and the page's URL. This approach will work beautifully for all users whosebrowsers accept session-level cookies. Those who do not accept cookies, however, willhave a unique session ID generated for them on each page visit, thereby making thisnaming technique unworkable for them. For this article I'm just going to demonstrate

    using the SessionID / URL file name scheme, although it won't work for those whosebrowsers are configured not to accept cookies. Also, it won't work for a Web farm unlessall servers store the view state files to a centralized location.

    Note One workaround would be to use a globally unique identifier (GUID) as the filename for the persisted view state, saving this GUID in a hidden form field on theASP.NET Web page. This approach, unfortunately, would take quite a bit more effortthan using theSessionID/ URL scheme, since it involves injecting a hidden form field into the Web Form. For thatreason, I'll stick to illustrating the simpler approach for this article.

  • 7/29/2019 50857887-asp-net

    22/91

    The second challenge arises because, each time a user visits a different page, a new fileholding that page's view state will be created. Over time this will lead to thousands offiles. Some sort of automated task would be needed to periodically clean out the viewstate files older than a certain date. I leave this as an exercise for the reader.

    To persist view state information to a file, we start by creating a class that derives fromthe Page class. This derived class, then, needs to override the

    SavePageStateToPersistenceMedium() and

    LoadPageStateFromPersistenceMedium() methods. The following code presents sucha class:

    CopypublicclassPersistViewStateToFileSystem:Page{

    protectedoverridevoidSavePageStateToPersistenceMedium(objectviewState)

    {

    // serializetheviewstateintoabase-64encodedstringLosFormatterlos=newLosFormatter();StringWriterwriter=new StringWriter();los.Serialize(writer,viewState);// savethestringtodiskStreamWritersw=File.CreateText(ViewStateFilePath);sw.Write(writer.ToString());sw.Close();

    }protectedoverrideobjectLoadPageStateFromPersistenceMedium(){

    // determinethefiletoaccessif(!File.Exists(ViewStateFilePath))

    returnnull;

    else{

    // openthefileStreamReadersr=File.OpenText(ViewStateFilePath);stringviewStateString=sr.ReadToEnd();sr.Close();// deserializethestringLosFormatterlos=newLosFormatter();returnlos.Deserialize(viewStateString);

    }}publicstring ViewStateFilePath{

    get{stringfolderName=Path.Combine(Request.PhysicalApplicationPath,"PersistedViewState");

    stringfileName= Session.SessionID + "-" +Path.GetFileNameWithoutExtension(Request.Path).Replace("/","-") + ".vs";

    returnPath.Combine(folderName,fileName);}

  • 7/29/2019 50857887-asp-net

    23/91

    }}

    The class contains a public property ViewStateFilePath, which returns the physicalpath to the file where the particular view state information will be stored. This file path is

    dependent upon the user's SessionID and the URL of the requested page.

    Notice that the SavePageStateToPersistenceMedium() method accepts an object

    input parameter. This object is the view state object that is built up from the save view

    state stage. The job ofSavePageStateToPersistenceMedium() is to serialize this objectand persist it in some manner. The method's code simply creates an instance of the

    LosFormatter object and invokes its Serialize() method, serializing the passed-in

    view state information to the StringWriterwriter. Following that, the specified file iscreated (or overwritten, if it already exists) with the contents of the base-64 encoded,serialized view state string.

    The LoadPageStateFromPersistenceMedium() method is called at the beginning of theload view state stage. Its job is to retrieve the persisted view state and deserialize backinto an object that can be propagated into the page's control hierarchy. This isaccomplished by opening the same file where the persisted view state was stored on the

    last visit, and returning the deserialized version via the Deserialize() method in

    LosFormatter().

    Again, this approach won't work with users that do not accept cookies, but for those thatdo, the view state is persisted entirely on the Web server's file system, thereby adding 0bytes to the overall page size!

    Note Another approach to reducing the bloat imposed by view state is to compress theserialized view state stream in theSavePageStateToPersistenceMedium()method, and then decompress it back to its original form in theLoadPageStateFromPersistenceMedium()method. Scott Galloway has ablog entry where he discusses his experiences with using#ziplib library to compress the view state.

    Parsing the View State

    When a page is rendered, it serializes its view state into a base-64 encoded string usingthe LosFormatter class and (by default) stores it in a hidden form field. On postback, thehidden form field is retrieved and deserialized back into the view state's objectrepresentation, which is then used to restore the state of the controls in the controlhierarchy. One detail we have overlooked up to this point in the article is what, exactly, is

    the structure of the Page class's view state object?

  • 7/29/2019 50857887-asp-net

    24/91

    As we discussed earlier, entire view state of the Page is the sum of the view state of thecontrols in its control hierarchy. Put another way, at any point in the control hierarchy,the view state of that control represents the view state of that control along with the view

    state of all of its children controls. Since the Page class forms the root of the controlhierarchy, its view state represents the view state for the entire control hierarchy.

    The Page class contains a SavePageViewState(), which is invoked during the page life

    cycle's save view state stage. The SavePageViewState() method starts by creating aTriplet that contains the following three items:

    1. The page's hash code. This hash code is used to ensure that the view state hasn'tbeen tampered with between postbacks. We'll talk more about view state hashingin the "View State and Security Implications" section.

    2. The collective view state of the Page's control hierarchy.3. An ArrayList of controls in the control hierarchy that need to be explicitly

    invoked by the page class during the raise postback event stage of the life cycle.

    The First and Third items in the Triplet are relatively straightforward; the Second

    item is where the view state for the Page's control hierarchy is maintained. The Second

    item is generated by the Page by calling the SaveViewStateRecursive() method, which

    is defined in the System.Web.UI.Control class. SaveViewStateRecursive() saves theview state of the control and its descendents by returning a Triplet with the followinginformation:

    1. The state present in the Control's ViewStateStageBag.2. An ArrayList of integers. This ArrayList maintains the indexes of the

    Control's child controls that have a non-null view state.

    3. An ArrayList of the view states for the children controls. The ith view state inthis ArrayList maps to the child control index in the ith item in the ArrayList in

    the Triplet's Second item.

    The Control class computes the view state, returning a Triplet. The Second item of the

    Triplet contains the view state of the Control's descendents. The end result is that the

    view state is comprised of many ArrayLists inside ofTriplets inside ofTriplets,

    inside ofTriplets, inside of... (The precise contents in the view state depend on thecontrols in the hierarchy. More complex controls might serialize their own state to the

    view state using Pairs orobject arrays. As we'll see shortly, though, the view state is

    composed of a number ofTriplets and ArrayLists nested as deep as the control

    hierarchy.)

    Programmatically Stepping Through the View State

    With just a little bit of work we can create a class that can parse through the view stateand display its contents. The download for this article includes a class called

    ViewStateParser that provides such functionality. This class contains a

  • 7/29/2019 50857887-asp-net

    25/91

    ParseViewState() method that recursively steps through the view state. It takes in threeinputs:

    1. The current view state object.2. How many levels deep we are in the view state recursion.

    3. A text label to display.

    The last two input parameters are just for display purposes. The code of this method,shown below, determines the type of the current view state object and displays thecontents of the view state accordingly, by recursively calling itself on each of the current

    object's members. (The variable tw is a TextWriter instance to which the output is beingwritten.)

    CopyprotectedvirtualvoidParseViewStateGraph(objectnode,intdepth,stringlabel)

    {

    tw.Write(System.Environment.NewLine);if(node==null){

    tw.Write(String.Concat(Indent(depth),label,"NODE IS NULL"));}elseif(nodeis Triplet){

    tw.Write(String.Concat(Indent(depth),label,"TRIPLET"));ParseViewStateGraph(((Triplet)node).First,depth+1,"First:");

    ParseViewStateGraph(((Triplet)node).Second,depth+1,"Second:");

    ParseViewStateGraph(((Triplet)

    node).

    Third,

    depth

    +1,"Third:

    ");

    }elseif(nodeisPair){

    tw.Write(String.Concat(Indent(depth),label,"PAIR"));ParseViewStateGraph(((Pair)node).First,depth+1,"First:");ParseViewStateGraph(((Pair)node).Second,depth+1,"Second:");

    }elseif(nodeis ArrayList){

    tw.Write(String.Concat(Indent(depth),label,"ARRAYLIST"));// display array valuesfor(inti= 0;i

  • 7/29/2019 50857887-asp-net

    26/91

    e.Current,depth+1, String.Format("({0})",count++));}elseif(node.GetType().IsPrimitive || nodeisstring){

    tw.Write(String.Concat(Indent(depth),label));tw.Write(node.ToString() + "(" +node.GetType().ToString() + ")");

    }else{

    tw.Write(String.Concat(Indent(depth),label,"OTHER-"));tw.Write(node.GetType().ToString());

    }}

    As the code shows, the ParseViewState() method iterates through the expected types

    Triplet, Pair, ArrayList, arrays, and primitive types. For scalar valuesintegers,strings, etc.the type and value are displayed; for aggregate typesarrays, Pairs,

    Triplets, etc.the members that compose the type are displayed by recursivelyinvoking ParseViewState().

    The ViewStateParser class can be utilized from an ASP.NET Web page (see the

    ParseViewState.aspx demo), or can be accessed directly from the

    SavePageStateToPersistenceMedium() method in a class that is derived from the Page

    class (see the ShowViewState class). Figures 8 and9 show the ParseViewState.aspxdemo in action. As Figure 8 shows, the user is presented with a multi-line textbox into

    which they can paste the hidden __VIEWSTATE form field from some Web page. Figure 9shows a snippet of the parsed view state for a page displaying file system information in aDataGrid.

    Figure 8. Decoding ViewState

  • 7/29/2019 50857887-asp-net

    27/91

    Figure 9. ViewState decoded

    In addition to the view state parser provided in this article's download, Paul Wilsonprovides a view state parseron his Web site. Fritz Onion also has a view state decoderWinForms application available for download from the Resources section on his Website.

    View State and Security Implications

    The view state for an ASP.NET Web page is stored, by default, as a base-64 encodedstring. As we saw in the previous section, this string can easily be decoded and parsed,displaying the contents of the view state for all to see. This raises two security-relatedconcerns:

  • 7/29/2019 50857887-asp-net

    28/91

    1. Since the view state can be parsed, what's to stop someone from changing thevalues, re-serializing it, and using the modified view state?

    2. Since the view state can be parsed, does that mean I can't place any sensitiveinformation in the view state (such as passwords, connection strings, etc.)?

    Fortunately, the LosFormatter class has capabilities to address both of these concerns, aswe'll see over the next two sections. Before we delve into the solutions for theseconcerns, it is important to first note that view state should only be used to store non-sensitive data. View state does not house code, and should definitely not be used to placesensitive information like connection strings or passwords.

    Protecting the View State from Modification

    Even though view state should only store the state of the Web controls on the page andother non-sensitive data, nefarious users could cause you headaches if they couldsuccessfully modify the view state for a page. For example, imagine that you ran an

    eCommerce Web site that used a DataGrid to display a list of products for sale along withtheir cost. Unless you set the DataGrid's EnableViewState property to False, theDataGrid's contentsthe names and prices of your merchandisewill be persisted in theview state.

    Nefarious users could parse the view state, modify the prices so they all read $0.01, andthen deserialize the view state back to a base-64 encoded string. They could then send oute-mail messages or post links that, when clicked, submitted a form that sent the user toyour product listing page, passing along the altered view state in the HTTP POSTheaders. Your page would read the view state and display the DataGrid data based on thisview state. The end result? You'd have a lot of customers thinking they were going to be

    able to buy your products for only a penny!

    A simple means to protect against this sort of tampering is to use a machineauthentication check, or MAC. Machine authentication checks are designed to ensure thatthe data received by a computer is the same data that it transmitted outnamely, that ithasn't been tampered with. This is precisely what we want to do with the view state. With

    ASP.NET view state, the LosFormatter performs a MAC by hashing the view state databeing serialized, and appending this hash to the end of the view state. (A hash is a quicklycomputed digest that is commonly used in symmetric security scenarios to ensure

    message integrity.) When the Web page is posted back, the LosFormatter checks toensure that the appended hash matches up with the hashed value of the deserialized view

    state. If it does not match up, the view state has been changed en route.

    By default, the LosFormatter class applies the MAC. You can, however, customize

    whether or not the MAC occurs by setting the Page class's EnableViewStateMacproperty. The default, True, indicates that the MAC should take place; a value of Falseindicates that it should not. You can further customize the MAC by specifying what

    hashing algorithm should be employed. In the machine.config file, search for the

    element's validation attribute. The default hashing algorithm used is

  • 7/29/2019 50857887-asp-net

    29/91

    SHA1, but you can change it to MD5 if you like. (For more information on the SHA1,see RFC 3174; for more information on MD5, read RFC 1321.)

    Note When usingServer.Transfer()

    you may find you receive a problem with view state authentication. A number of articlesonline have mentioned that the only workaround is to setEnableViewStateMacto False. While this will certainly solve the problem, it opens up a security hole. For moreinformation, including a secure workaround, consult this KB article.

    Encrypting the View State

    Ideally the view state should not need to be encrypted, as it should never contain sensitive

    information. If needed, however, the LosFormatter does provide limited encryption

    support. The LosFormatter only allows for a single type of encryption: Triple DES. To

    indicate that the view state should be encrypted, set the element'svalidation attribute in the machine.config file to 3DES.

    In addition to the validation attribute, the element contains

    validationKey and decryptionKey attributes, as well. The validationKey attribute

    specifies the key used for the MAC; decryptionKey indicates the key used in the TripleDES encryption. By default, these attributes are set to the value"AutoGenerate,IsolateApp," which uniquely autogenerates the keys for each Webapplication on the server. This setting works well for a single Web server environment,but if you have a Web farm, it's vital that all Web servers use the same keys for MACand/or encryption and decryption. In this case you'll need to manually enter a shared key

    among the servers in the Web farm. For more information on this process, and the element in general, refer to the technical documentationand Susan Warren's article Taking a Bite Out of ASP.NET ViewState.

    The ViewStateUserKey Property

    Microsoft ASP.NET version 1.1 added an additional Page class property

    ViewStateUserKey. This property, if used, must be assigned a string value in the

    initialization stage of the page life cycle (in the Page_Init event handler). The point ofthe property is to assign some user-specific key to the view state, such as a username. The

    ViewStateUserKey, if provided, is used as a salt to the hash during the MAC.

    What the ViewStateUserKey property protects against is the case where a nefarious uservisits a page, gathers the view state, and then entices a user to visit the same page,passing in their view state (see Figure 10). For more information on this property and itsapplication, refer to Building Secure ASP.NET Pages and Controls.

  • 7/29/2019 50857887-asp-net

    30/91

    Figure 10. Protecting against attacks using ViewStateUserKey

  • 7/29/2019 50857887-asp-net

    31/91

    Conclusion

    In this article we examined the ASP.NET view state, studying not only its purpose, butalso its functionality. To best understand how view state works, it is important to have afirm grasp on the ASP.NET page life cycle, which includes stages for loading and saving

    the view state. In our discussions on the page life cycle, we saw that certain stagessuchas loading postback data and raising postback eventswere not in any way related toview state.

    While view state enables state to be effortlessly persisted across postbacks, it comes at acost, and that cost is page bloat. Since the view state data is persisted to a hidden formfield, view state can easily add tens of kilobytes of data to a Web page, thereby increasingboth the download and upload times for Web pages. To cut back on the page weightimposed by view state, you can selectively instruct various Web controls not to record

    their view state by setting the EnableViewState property to False. In fact, view state can

    be turned off for an entire page by setting the EnableViewState property to false in the

    @Page directive. In addition to turning off view state at the page-level or control-level,you can also specify an alternate backing store for view state, such as the Web server'sfile system.

    This article wrapped up with a look at security concerns with view state. By default, theview state performs a MAC to ensure that the view state hasn't been tampered with

    between postbacks. ASP.NET 1.1 provides the ViewStateUserKey property to add anadditional level of security. The view state's data can be encrypted using the Triple DESencryption algorithm, as well.

    Happy Programming!

    Works Consulted

    There are a number of good resources for learning more about ASP.NET view state. PaulWilson has provided a number of resources, such as View State: All You Wanted toKnow, and the Page View State Parser. Dino Esposito authored an article forMSDNMagazine in February, 2003, titled The ASP.NET View State, which discusses atechnique for storing view state on the Web server's file system. Taking a Bite Out ofASP.NET View State, written by Susan Warren, provides a good high-level overview ofthe view state, including a discussion on encrypting the view state. Scott Galloway's bloghas some good posts on working with ASP.NET view state, too.

    Special Thanks To...

    Before submitting my article to my MSDN editor I have a handful of volunteers helpproofread the article and provide feedback on the article's content, grammar, anddirection. Primary contributors to the review process for this article include James Avery,Bernard Vander Beken, Dave Donaldson, Scott Elkin, and Justin Lovell. If you are

  • 7/29/2019 50857887-asp-net

    32/91

    interested in joining the ever-growing list of reviewers, drop me a line [email protected].

    About the Author

    Scott Mitchell, author of five books and founder of 4GuysFromRolla.com, has beenworking with Microsoft Web technologies for the past five years. Scott works as anindependent consultant, trainer, and writer. He can be reached [email protected] or via his blog, which can be found athttp://ScottOnWriting.NET.

    Related Books

    y ASP. NET: Tips, Tutorials, & Codey Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Teamy ASP.NET Unleashed

    y Programming Microsoft ASP.NET

    2011 Microsoft. All rights reserved.

    Terms of Use | Trademarks | Privacy Statement | Feedback

    ASP.NET Web Services

    Introduction

    We can now use ASP.NET to create Web Service that is based on industrial standardsincluded XML, SOAP and WSDL.

    ASP.NET Web Services support clients using HTTP-POST, HTTP-GET and SOAPprotocols to invoke methods exposed, depends on your specific requirement you chooseone method over the others. The main difference between HTTP-GET or HTTP-POSTand SOAP is the data types supported by SOAP is much richer because SOAP used XSD

    schema to represent complex data types.

    Here are samples codes I use to test the building of ASP.NET Web Service:

    Step 1: Create the ASP.NET Web Service Source File

    ASP.NET Web Service file name has extension asmx and my file is namedMyWebService.asmx, source is listed as follows:

  • 7/29/2019 50857887-asp-net

    33/91

    File: MyWebService.asmx

    Collapse

    using System.Web.Services;

    publicclassMyClass{

    [WebMethod()]public int Add(inta, int b){

    returna + b;}

    }

    The page directive WebService is required and class is the name of the .NET Class toexpose the Web Service, each method exposes as Web Service Class Method need to

    have a declarative attribute statement [WebMethod()] in front of it. Here the .NET Classimplementation is included in the same file with ASP.NET Web Service file but it is not

    mandatory and we can choose to include an external .NET Assembly to implement theservice as the following example:

    File: MyWebService2.asmx

    Collapse

    The fileMyWebService2.asmx is referencing another .NET AssemblyMyWebServiceImplwhich is located under the/bin ASP.NET Application sub-folder (note that the defaultlocation for Assemblies in ASP.NET is /bin sub-folder under each ASP.NET

    Applications). The source of .NET AssemblyMyWebServiceImplis written by C# and islisted as follows:

    File: MyWebServiceImpl.cs

    CollapsenamespaceMyWebService{

    using System;

    using System.Web.Services;

    publicclassMyStringReverse: WebService{

    [WebMethod(Description="Reverse String")]public StringReverseString( String InString){

    // Checknull Stringif( InString==null) returnnull;

  • 7/29/2019 50857887-asp-net

    34/91

    Int32intSize= InString.Length;char[]arrayInString= InString.ToCharArray();char[]arrayOutString=newchar[intSize];

    for(Int32i= 0 ;iCSC /t:library /out:bin/MyWebServiceImpl.dllMyWebServiceImpl.cs

    The following sections I will continue useMyWebService.asmx as my experimental WebService.

    Step 2: Create the ASP.NET Web Service Clients

    There are many ways to consume Web Services and have three examples. The first oneuses HTTP-POST protocol and it has advantage to coexist with todays application quitewell and use HTTP-GET is similar and I let reader to try it. The second one uses SOAPProxy Client Object generated by WSDL utility and it provides programmers with theirfamiliar object modal that they call methods provided by the generated Proxy Interface.

    The final one uses SOAP standard request message and it parses SOAP response messagewith the help of XMLHTTP COM object that is installed by Microsoft XML Parser 3.0.

    Client use HTTP-POST Method

    The example is an ASP.NET page TestWebService.aspx and source listing as follows:

    File: TestWebService.aspx

    Collapse

  • 7/29/2019 50857887-asp-net

    35/91

    The ASP page accepts parameters from browser and calls the Addmethod of the WebServiceMyWebService via the HTTP-POST protocol, the result will be XML message

    and need further parsing by the client application. To parse the response, client can useeither Java XML parser in applet or use IE5s DOM Object.

    The following is an example of XML response when parameters a=1, b=2 are inputted:

    Collapse3

    Client use WSDL Generated Proxy Object

    If your client will be Windows applications or ASP.NET applications, you can useWSDL.EXE utility to created standard .NET Assemble to provide Proxy Class for yourclients.

    Here are steps you can follow and try:

    Use WSDL.EXE utility to create the Proxy Class source file in any language you havechosen and here I use C# and command as follows:

    CollapseC:\>wsdl /language:C# /out:MyProxyClass.cs

    http://localhost/ASP.NET/MyWebService.asmx

    MyProxyClass.cs is generated and source listing as follows:

    File: MyProxyClass.cs

    Collapse//------------------------------------------------------------------------------// // Thiscodewasgeneratedby atool.// Runtime Version:1.0.2914.16

    //// Changestothisfilemay causeincorrectbehaviorandwillbelostif// thecodeisregenerated.// //------------------------------------------------------------------------------

    //// Thissourcecodewasauto-generatedby wsdl, Version=1.0.2914.16.

  • 7/29/2019 50857887-asp-net

    36/91

    //using System.Diagnostics;using System.Xml.Serialization;using System;using System.Web.Services.Protocols;using System.Web.Services;

    [System.Web.Services.WebServiceBindingAttribute(Name="MyClassSoap",Namespace="http://tempuri.org/")]publicclassMyClass:System.Web.Services.Protocols.SoapHttpClientProtocol {

    [System.Diagnostics.DebuggerStepThroughAttribute()]publicMyClass() {

    this.Url="http://localhost/ASP.NET/MyWebService.asmx";}

    [System.Diagnostics.DebuggerStepThroughAttribute()]

    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://temp

    uri.org/Add",

    Use=System.Web.Services.Description.SoapBindingUse.Literal,

    ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]

    publicint Add(inta,intb) {object[]results=this.Invoke("Add",newobject[] {

    a,b});

    return((int)(results[0]));}

    [System.Diagnostics.DebuggerStepThroughAttribute()]public System.IAsyncResultBeginAdd(inta,intb,

    System.AsyncCallbackcallback,objectasyncState) {returnthis.BeginInvoke("Add",newobject[] {

    a,b},callback,asyncState);

    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]publicint EndAdd(System.IAsyncResultasyncResult) {

    object[]results=this.EndInvoke(asyncResult);return((int)(results[0]));

    }}

    Then we need to create the .NET Assembly for used by clients:

    CollapseC:\>csc /t:library MyProxyClass.cs

    The above command will compile the source and createMyProxyClass.dlllibrary file.

  • 7/29/2019 50857887-asp-net

    37/91

    I use ASP to depict how to use the proxy object and the file isTestWebServiceWithProxy.aspx source listing as follows:

    File: TestWebServiceWithProxy.aspx

    Collapse

    voidbtn_click(Objectsource, EventArgse){

    MyClassmycls=newMyClass();intx= Int32.Parse(a.Text);int y = Int32.Parse(b.Text);

    Message.Text=mycls.Add(x, y).ToString();}

    Client use XMLHTTP to call Web service via SOAP

    To fully explore the SOAP capability, you may choose to call your ASP.NET WebService via SOAP core protocol and here I provide another example for reference.

    To test the ASP.NET service with SOAP protocol, I create an ASP client fileTestWebServiceByXML.asp and its source is listed as follows:

    File: TestWebServiceByXML.asp

    Collapse

    functionbtn_click(a,b){

    varxmlObj=new ActiveXObject("Msxml2.DOMDocument");varsXml ="";

    sXml +="

  • 7/29/2019 50857887-asp-net

    38/91

    sXml +="xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";

    sXml +="xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";

    sXml +="";sXml +="";sXml=sXml + "" + a.value + "";sXml=sXml + "" + b.value + "";sXml +=""

    // Try toparsetheXMLstringinto DOMobjectxmlObj.loadXML(sXml);

    //ToseethevalidatedXMLstringiswell-formedXmlRequest.innerText= xmlObj.xml ;

    varxmlHTTP=new ActiveXObject("Msxml2.XMLHTTP");xmlHTTP.Open("Post",

    "http://localhost/ASP.NET/MyWebService.asmx",false);xmlHTTP.setRequestHeader("SOAPAction",

    "http://tempuri.org/Add");xmlHTTP.setRequestHeader("Content-Type","text/xml;

    charset=utf-8");xmlHTTP.Send(xmlObj.xml);MyResult.innerText= xmlHTTP.responseText;

    varxmlResponse=xmlHTTP.responseXML;answer.innerText=

    xmlResponse.selectSingleNode("soap:Envelope/soap:Body/AddResponse/AddResult").text;

    }

    Pleaseinputa:

    Pleaseinputb:

    Answeris

    Request:

    Response:

    Here I installed Microsoft XML Parser 3.0 in my client machine that give me theXMLHTTP and DOM COM objects to test my application.

  • 7/29/2019 50857887-asp-net

    39/91

    Webservices

    http://msdn.microsoft.com/en-

    us/library/t745kdsh.aspx

    .NET Framework 4Other Versions

    y Visual Studio 2008y Visual Studio 2005

    Web services are components on a Web server that a client application can call bymaking HTTP requests across the Web. ASP.NET enables you to create custom Webservices or to use built-in application services, and to call these services from any clientapplication. We suggest the following progression of documentation to help you navigatethrough the related topics.

    Getting started

    y Introduction to Programming Web Services in Managed Code

    Describes the XML Web services programming model inmanaged code.

    y XML Web Services Using ASP.NET

    Provides links to information about how to create XML Webservices in ASP.NET, and about how they work.

    y Creating WCF Services for ASP.NET AJAX

    Describes Windows Communication Foundation (WCF)services that are hosted as ASP.NET compatible services.

    y Web References in Visual Studio

    Provides information about how to reference Web services in

  • 7/29/2019 50857887-asp-net

    40/91

    Visual Studio projects and about the proxy classes thatrepresent a Web service.

    Creating andusing Webservices

    y Walkthrough: Creating and Using an ASP.NET Web Service inVisual Web Developer

    Provides a step-by-step tutorial on how to create an ASP.NETWeb service and how to call it.

    y How to: Add and Remove Web References

    Describes how to use tools in Visual Studio to create a proxyclass for a Web service.

    y How to: Call a Web Service

    Describes how to call Web service methods.

    Creating andusing Webservices in AJAX

    y Using Web Services in ASP.NET AJAX

    Describes ASP.NET Web services, which are ASP.NET andWindows Communication Foundation (WCF) custom servicesthat are called from client script that runs in AJAX-enabledASP.NET Web pages.

    y Walkthrough: Creating and AJAX-enabled Web Service

    Shows how to create an AJAX-enabled Web service in VisualStudio and how to create a Web page that calls the Web service

    by using client script.

    y Exposing Web Services to Client Script

    Shows how to make a Web service available to client scriptthat runs in the browser.

    y Exposing WCF Services to Client Script

    Shows how to make a WCF service available to client scriptthat runs in the browser.

    y Calling Web Services from Client Script

    Shows how to use AJAX functionality in ASP.NET to call aWeb service from client script that runs in the browser.

    Using applicationservices in AJAX

    y Using Forms Authentication with Microsoft Ajax

  • 7/29/2019 50857887-asp-net

    41/91

    Shows how to call the application authentication service fromclient script that runs in the browser.

    y Using Roles Information with Microsoft Ajax

    Shows how to call the application role service from client scriptthat runs in the browser.

    y Using Profile Information with Microsoft Ajax

    Shows how to call the application profile service from clientscript that runs in the browser.

    Using applicationservices as WCFservices

    y ASP.NET Application Services Overview

    Describes ASP.NET and Windows Communication Foundation(WCF) application services, which provide a consistent way to

    provide authentication, roles, and profile properties to anyclient in order to build service-oriented applications.

    y How to: Enable the WCF Authentication Service.

    Shows how to use the application authentication service as aWindows Communication Foundation (WCF) service.

    y How to: Enable the WCF Role Service.

    Shows how to use the application role service as a Windows

    Communication Foundation (WCF) service.

    y How to: Enable the WCF Profile Service.

    Shows how to use the application profile service as a WindowsCommunication Foundation (WCF) service.

    y Walkthrough: Using ASP.NET Application Services.

    Shows how to use the application services in a Windowsapplication.

    See Also

    Other Resources

    Web Services in ASP.NET AJAXCommunity Content AddFAQ

  • 7/29/2019 50857887-asp-net

    42/91

    2011 Microsoft. All rights reserved.Terms of Use | Trademarks | Privacy Statement | Feedback

    State Management Techniques in ASP.NET

    This article discusses various options for state management for web applicationsdeveloped using ASP.NET. Generally, web applications are based on stateless HTTPprotocol which does not retain any information about user requests. In typical clientand server communication using HTTP protocol, page is created each time the pageis requested.

    Developer is forced to implement various state management techniques when

    developing applications which provide customized content and which "remembers"the user.

    Here we are here with various options for ASP.NET developer to implement statemanagement techniques in their applications. Broadly, we can classify statemanagement techniques as client side state management or server side statemanagement. Each technique has its own pros and cons. Let's start with exploringclient side state management options.

    Client side State management Options:

    ASP.NET provides various client side state management options like Cookies,QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let'sdiscuss each of client side state management options.

    Bandwidth should be considered while implementing client side state managementoptions because they involve in each roundtrip to server. Example: Cookies areexchanged between client and server for each page request.

    Cookie:

    A cookie is a small piece of text stored on user's computer. Usually, information isstored as name-value pairs. Cookies are used by websites to keep track of visitors.Every time a user visits a website, cookies are retrieved from user machine and helpidentify the user.

    Let's see an example which makes use of cookies to customize web page.

    if(Request.Cookies["UserId"] != null)lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our

    website!";else

    lbMessage.text = "Guest,welcome to our website!";

  • 7/29/2019 50857887-asp-net

    43/91

    If you want to store client's information use the below code

    Response.Cookies["UserId"].Value=username;

    Advantages:

    y Simplicity

    Disadvantages:

    y Cookies can be disabled on user browsersy Cookies are transmitted for each HTTP request/response causing overhead on

    bandwidthy Inappropriate for sensitive data

    Hidden fields:

    Hidden fields are used to store data at the page level. As its name says, these fields

    are not rendered by the browser. It's just like a standard control for which you canset its properties. Whenever a page is submitted to server, hidden fields values arealso posted to server along with other controls on the page. Now that all the asp.netweb controls have built in state management in the form of view state and newfeature in asp.net 2.0 control state, hidden fields functionality seems to beredundant. We can still use it to store insignificant data. We can use hidden fields inASP.NET pages using following syntax

    protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

    //to assign a value to Hidden fieldHidden1.Value="Create hidden fields";

    //to retrieve a valuestring str=Hidden1.Value;

    Advantages:

    y Simple to implement for a page specific datay Can store small amount of data so they take less size.

    Disadvantages:

    y Inappropriate for sensitive datay Hidden field values can be intercepted(clearly visible) when passed over a

    network

    View State:

    View State can be used to store state information for a single user. View State is abuilt in feature in web controls to persist data between page post backs. You can setView State on/off for each control using EnableViewState property. By default,EnableViewState property will be set to true. View state mechanism posesperformance overhead. View state information of all the controls on the page will be

  • 7/29/2019 50857887-asp-net

    44/91

    submitted to server on each post back. To reduce performance penalty, disable ViewState for all the controls for which you don't need state. (Data grid usually doesn'tneed to maintain state). You can also disable View State for the entire page byadding EnableViewState=false to @page directive. View state data is encoded asbinary Base64 - encoded which add approximately 30% overhead. Care must betaken to ensure view state for a page is smaller in size. View State can be used using

    following syntax in an ASP.NET web page.

    // Add item to ViewStateViewState["myviewstate"] = myValue;

    //Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);

    Advantages:

    y Simple for page level datay Encryptedy

    Can be set at the control level

    Disadvantages:

    y Overhead in encoding View State valuesy Makes a page heavy

    Query strings:

    Query strings are usually used to send information from one page to another page.They are passed along with URL in clear text. Now that cross page posting feature isback in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a

    limit of 255 characters on URL length. We can only pass smaller amounts of datausing query strings. Since Query strings are sent in clear text, we can also encryptquery values. Also, keep in mind that characters that are not valid in a URL must beencoded using Server.UrlEncode.

    Let's assume that we have a Data Grid with a list of products, and a hyperlink in thegrid that goes to a product detail page, it would be an ideal use of the Query Stringto include the product ID in the Query String of the link to the product details page(for example, productdetails.aspx?productid=4).

    When product details page is being requested, the product information can beobtained by using the following codes:

    string productid;productid=Request.Params["productid"];

    Advantages:

    y Simple to Implement

  • 7/29/2019 50857887-asp-net

    45/91

    Disadvantages:

    y Human Readabley Client browser limit on URL lengthy Cross paging functionality makes it redundanty Easily modified by end user

    Control State:

    Control State is new mechanism in ASP.NET 2.0 which addresses some of theshortcomings of View State. Control state can be used to store critical, privateinformation across post backs. Control state is another type of state containerreserved for controls to maintain their core behavioral functionality whereas ViewState only contains state to maintain control's contents (UI). Control State sharessame memory data structures with View State. Control State can be propagatedeven though the View State for the control is disabled. For example, new control GridView in ASP.NET 2.0 makes effective use of control state to maintain the stateneeded for its core behavior across post backs. Grid View is in no way affected when

    we disable View State for the Grid View or entire page

    Server Side State management:

    As name implies, state information will be maintained on the server. Application,Session, Cache and Database are different mechanisms for storing state on theserver.

    Care must be taken to conserve server resources. For a high traffic web site withlarge number of concurrent users, usageof sessions object for state management can create load on server causingperformance degradation

    Application object:

    Application object is used to store data which is visible across entire application andshared across multiple user sessions. Data which needs to be persisted for entire lifeof application should be stored in application object.

    In classic ASP, application object is used to store connection strings. It's a greatplace to store data which changes infrequently. We should write to applicationvariable only in application_Onstart event (global.asax) or application.lock event toavoid data conflicts. Below code sample gives idea

    Application.Lock();Application["mydata"]="mydata";Application.UnLock();

    Session object:

    Session object is used to store state specific information per client basis. It is specificto particular user. Session data persists for the duration of user session you canstore session's data on web server in different ways. Session state can be configured

  • 7/29/2019 50857887-asp-net

    46/91

    using the section in the application's web.config file.

    Configuration information:

  • 7/29/2019 50857887-asp-net

    47/91

    servery Out-of-process mode- session state is held in a process called

    aspnet_state.exe that runs as a windows service.y Database mode session state is maintained on a SQL Server database.

    In process mode:

    This mode is useful for small applications which can be hosted on a single server.This model is most common and default method to store session specific information.Session data is stored in memory of local web server

    Configuration information:

    Advantages:

    y Fastest modey Simple configuration

    Disadvantages:

    y Session data will be lost if the worker process or application domain recyclesy Not ideal for web gardens and web farms

    Out-of-process Session mode (state server mode):

    This mode is ideal for scalable and highly available applications. Session state is held

    in a process called aspnet_state.exe that runs as a windows service which listens onTCP port 42424 by default. You can invoke state service using services MMC snap-inor by running following net command from command line.

    Net start aspnet_state

    Configuration information:

    Advantages:

    y Supports web farm and web garden configurationy Session data is persisted across application domain recycles. This is achieved

    by using separate worker process for maintaining state

  • 7/29/2019 50857887-asp-net

    48/91

    Disadvantages:

    y Out-of-process mode provides slower access compared to In processy Requires serializing data

    SQL-Backed Session state:

    ASP.NET sessions can also be stored in a SQL Server database. Storing sessions inSQL Server offers resilience that can serve sessions to a large web farm that persistsacross IIS restarts.

    SQL based Session state is configured with aspnet_regsql.exe. This utility is locatedin .NET Framework's installed directoryC:\\microsoft.net\framework\. Running this utility will createa database which will manage the session state.

    Configuration Information:

    Advantages:

    y Supports web farm and web garden configurationy Session state is persisted across application domain recycles and even IIS

    restarts when session is maintained on different server.

    Disadvantages:

    y Requires serialization of objects

    Choosing between client side and Server side management techniques is driven byvarious factors including available server resources, scalability and performance. Wehave to leverage both client side and server side state management options to buildscalable applications.

    When leveraging client side state options, ensure that little amount of insignificantinformation is exchanged between page requests.

    Various parameters should be evaluated when leveraging server side state optionsincluding size of application, reliability and robustness. Smaller the application, In

    process is the better choice. We should account in the overheads involved inserializing and deserializing objects when using State Server and Database basedsession state. Application state should be used religiously.

    Comment Request!Thank you for reading this post. Please post your feedback, question, or comments about thispost Here.

    Login to add your contents and source code to this article

  • 7/29/2019 50857887-asp-net

    49/91

    About the author

    Santhosh Babu

    Looking for C# Consulting?

    C# Consulting is founded in 2002 by thefounders of C# Corner. Unlike a traditionalconsulting company, our consultants arewell-known experts in .NET and many ofthem are MVPs, authors, and trainers. Wespecialize in Microsoft .NET developmentand utilize Agile Development andExtreme Programming practices to providefast pace quick turnaround results. Oursoftware development model is a mix ofAgile Development, traditional SDLC, and

    Waterfall models.Click here to learn more about C#

    Consulting.

    Introducing MaxV - one click. infinite control. Hyper-V Hosting fromMaximumASP.Finally a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on.Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.Climb aboard the MaxV platform and take advantage of High Availability, IntelligentMonitoring, Recurrent Backups, and Scalability with no hassle or hidden fees. As amanaged hosting partner focused solely on Microsoft technologies since 2000,MaximumASP is uniquely qualified to provide the superior support that our business isbuilt on. Unparalleled expertise with Microsoft technologies lead to working directlywith Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment;partnering in the Go Live Program for Hyper-V; and product co-launches built on WS2008 with Hyper-V technology.

    Dynamic PDFceTE software specializes in components for dynamic PDF generation andmanipulation. The DynamicPDF product line allows you to dynamically generatePDF documents, merge PDF documents and new content to existing PDF documents

    from within your applications.SQL and .NET performance profiling in one placeInvestigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, soyou can see which is causing the problem without switching tools.

    Go.NETBuild custom interactive diagrams, network, workflow editors, flowcharts, or softwaredesign tools. Includes many predefined kinds of nodes, links, and basic shapes.

  • 7/29/2019 50857887-asp-net

    50/91

    Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-placeediting, tooltips, grids, printing, overview window, palette. 100% implemented in C# asa managed .NET Control. Document/View/Tool architectu

    ASP.NET AuthenticationVisual Studio .NET 2003

    ASP.NET implements additional authentication schemes using authentication providers,which are separate from and apply only after the IIS authentication schemes. ASP.NETsupports the following authentication providers:

    y Windows (default)y Formsy Passport

    y None

    To enable an authentication provider for an ASP.NET application, use the authenticationelement in either machine.config or Web.config as follows:

    Copy

    Each ASP.NET authentication provider supports an OnAuthenticate event that occurs

    during the authentication process, which you can use to implement a customauthorization scheme. The primary purpose of this event is to