State – Part 2 (Session State)

September 29, 2010 § 1 Comment

So, we’ve already discussed View State; let’s continue with a discussion of Session State. While discussing View State, we talked about the fact that View State is stored in hidden fields within the HTML page, and this has both positive and negative effects.

Objects in Session are good for the life of the session, rather than the life of the page (as they are with View State). This is an important distinction, and often drives the decision to use either View State or Session state.

Session objects are stored server side on a per-user basis. Typically, the session is stored In-Process (or within the ASP.NET worker process – either aspnet_wp.exe or w3wp.exe, depending on which version of IIS you are using). There are multiple options for storing Session besides In-Process, but that discussion is an entire post in and of itself.

So to start with, how does session work? Well, assuming your application has Session State enabled (which is the default, although you can disable it), a session id is automatically generated when the user first accesses the site, and that session id is transmitted between the client and the server on every request/response. That session id is also tied to a server-side hashtable, which can be accessed with the Session object.

This has some similarities with the technique that we discussed when talking about View State, wherein you transmit a small identifier between the client and server, and fetch the object from (or save the object to) the database for storage. Using Session streamlines the process, and yields some architectural and performance advantages over that technique.  For instance, this pattern using Session State is perfectly acceptable and performant because only the session id is transmitted to and from the client while the actual object remains on the server.

public partial class Example : System.Web.UI.Page 
{
    public Customer Customer
    {
        get
        {
            return Session["Customer"];
        }
        set
        {
            Session["Customer"] = value;
        }
    }
}
The session id can be transmitted to and from the client in one of two ways. You can either transmit the session id using a cookie (which is the default), or you can opt not to use a cookie. There really isn’t a significant difference between the two techniques. With the first, the session id is in a cookie, which is invisible (mostly) to the user. With the second, the session id is injected into the url, which is visible to the user. So, if we navigate Firefox to Visual Studio Magazine, for instance, we can view the individual cookies, and see something like this: Cookies in Firefox

The cookieless version can be preferable, as it is possible to deny cookies with a browser setting, effectively making your site unusable for anyone that does have cookies disabled in their browser. In order to switch to the cookieless version, you simply need to modify your web.config file.

<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
      <sessionState cookieless="true"/>
        ...
    </system.web>
</configuration>
<!–
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0??;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;??\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;??\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;??\red192\green192\blue192;}??\fs20 \cf2 public\cf0  \cf2 partial\cf0  \cf2 class\cf0  \cf10 Example\cf0  : System.Web.UI.\cf10 Page\cf0  \par ??\{\par ??    \cf2 public\cf0  Customer Customer\par ??    \{\par ??        \cf2 get\par ??\cf0         \{\par ??            \cf2 return\cf0  Session[\cf13 “Customer”\cf0 ];\par ??        \}\par ??        \cf2 set\par ??\cf0         \{\par ??            Session[\cf13 “Customer”\cf0 ] = \cf2 value\cf0 ;\par ??        \}\par ??    \}\par ??\}}
–>
<div style=”font-family: Courier New; font-size: 10pt; color: black; background: white;”>
<pre style=”margin: 0px;”><span style=”color: blue;”>public</span> <span style=”color: blue;”>partial</span> <span style=”color: blue;”>class</span> <span style=”color: teal;”>Example</span> : System.Web.UI.<span style=”color: teal;”>Page</span> </pre>
<pre style=”margin: 0px;”>{</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; <span style=”color: blue;”>public</span> Customer Customer</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; {</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style=”color: blue;”>get</span></pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style=”color: blue;”>return</span> Session[<span style=”color: maroon;”>”Customer”</span>];</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style=”color: blue;”>set</span></pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session[<span style=”color: maroon;”>”Customer”</span>] = <span style=”color: blue;”>value</span>;</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style=”margin: 0px;”>&nbsp;&nbsp;&nbsp; }</pre>
<pre style=”margin: 0px;”>}</pre>
</div>

There are, of course, some potential issues with using session state, particularly when in a web garden or web farm environment. In the next article in this series, we’ll discuss this problem further and some ways to mitigate or eliminate those issues.

State – an introduction

September 22, 2010 § 1 Comment

Understanding and being able to properly manipulate state in a web application is crucial to building a functional web application that is performant and scalable. I wonder if the ASP.NET padding oracle attack would have been less of an issue had more people been aware of state and how different options affect performance, scalability, and security. Articles like this one from 4 Guys discussing Forms Authentication that include terms and phrases like “automagically” and “ASP.NET does most of the work from there!” tend to exacerbate the issue:

…One of the new features of ASP.NET is Forms Authentication. Like in classic ASP, where custom database authentication occurred through the user entering his or her login credentials via an HTML form, ASP.NET Forms Authentication works similarly. However, using this neat feature, many of the mundane tasks and code that you were required to write in classic ASP are handled for you automagically.

Forms Authentication in ASP.NET is handled by a special FormsAuthentication class. This class contains a number of static (or Shared) methods that allow you to identify users via a login form. You can easily configure your ASP.NET application to use Forms Authentication by simply specifying a location (URL) for your login form – ASP.NET does most of the work from there! When an unauthenticated user visits a restricted page on your Web site they will be automatically directed to the specified login form. Once they successfully log on, you can optionally issue an authentication cookie to prevent authenticated users from having to log in time and time again….

The thing is that it isn’t “automagic”, though. Understanding that when you save a piece of data it’s going to go somewhere, and knowing where, can make the difference between a barely functioning web app and one that performs well while scaling to meet the needs of however many users you need to throw at it.

One of my favorite interview questions is, “Please talk to me about state and how to manage it in a web application.” The answer to this question tells me a ridiculous amount of information about the interviewee. If they go into a lengthy explanation comparing View State and Session State and continuing on to discuss different options for storing Session State, then we’ll continue with the interview. If they response with a blank state and, “Well, you can store stuff in the session.” then I politely end the interview and get back to work.

So tomorrow, a discussion of View State

Where Am I?

You are currently browsing entries tagged with session state at Mike Vallotton's Blog.