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>
- /// Summary description for GetSessionHelper
- /// </summary>
- public class SessionHelper : IRequiresSessionState
- {
- public SessionHelper()
- {
- //
- // TODO: Add constructor logic here
- //
- }
- /// <summary>
- /// Get Session values
- /// </summary>
- /// <param name="key">session key /// <returns>object value</returns>
- 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:
how to call this session variable in another class,give one example
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
Post a Comment