Adsence750x90

Wednesday, July 7, 2010

How to get Session Variable in Class File

How to get Session Variable in Class (.cs) File 

Normally Session is not accessible in Class file. when  one try to call Session in class file it return "Object reference not set to an instance of an object." error description like " An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code." this error is thrown by System.NullReferenceException. To access Session in class file Microsoft introduce a Interface IRequiresSessionState, derived from System.Web.SessionState



 The metadata of IRequiresSessionState


namespace System.Web.SessionState
{
    // Summary:
    //     Specifies that the target HTTP handler requires read and write access to
    //     session-state values. This is a marker interface and has no methods.
    public interface IRequiresSessionState
    {
    }
}




IRequiresSessionState Specifies that the target HTTP handler requires read and write access to session-state values. IRequiresSessionState has no methods.


How to Use



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
/// 
/// Summary description for GetSessionHelper
/// 
public class SessionHelper : IRequiresSessionState
{
    public SessionHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// 
    /// Get Session values
    /// 
    /// session key    /// object value
    public object GetSession(string key)
    {
        //check session 
        if (HttpContext.Current.Session[key] != null)
        {
            //return session value
            return HttpContext.Current.Session[key];
        }
        else
        {
            //return empty string
            return string.Empty;
        }
    }
}




Calling SessionHelper Class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Creating object of SessionHelper Class
        SessionHelper objSessionHelper = new SessionHelper();
        //setting session value in a variable
        string sessionValue = objSessionHelper.GetSession("test").ToString();
        //writing session value in Page
        Response.Write(sessionValue);
    }
}


2 comments:

Anonymous said...

how to call this session variable in another class,give one example

Anonymous said...

This is a nice solution but I would recommend reviewing this alternative:
http://stackoverflow.com/questions/621549/how-to-access-session-variables-from-any-class-in-asp-net