Just another tech site

ASP.NET Session Helper


The simpliest way to acces the session variable in an ASP.NET page is to call directely the SESSION variable and then to make the apropriate validation and convertion or casting.

int? sessionId = Page.Session["SessionId"]

But you get lazy and at some point you will forget ol the validation.
So here is an alternative where all the validation and convertion is done in a single place.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace LocalNameSpace.Custom.CustomBase
{
    public static class SessionHelper
    {
        public static int? SESSION_VARNAME
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context != null && context.Application["SESSION_VARNAME"] != null)
                {
                    int sessionId;
                    if (int.TryParse(context.Application["SESSION_VARNAME"].ToString(), out sessionId))
                    {
                        return sessionId;
                    }
                }
                return null;
            }
            set
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    context.Application["SESSION_VARNAME"] = value;
                }
            }
        }
    }
}

Now the call will look like.

int? sessionId = SessionHelper.SESSION_VARNAME;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: