Click here to Skip to main content
16,009,469 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
hi I want to check SESSION on controller Initialize method.

my code is

protected override void Initialize(RequestContext requestContext = null)
{

try
{
UserSession _UserSession = (UserSession)Session["user"];
if (_UserSession.MemberID == 0)
{

RedirectToAction("LogIn", "Account");
}
}
catch
{
RedirectToAction("LogIn", "Account");
}

//requestContext.RouteData = RedirectToAction("LogIn", "Account");

}

but through an error

Object reference not set to an instance of an object.
Description: 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.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

If i add
base.Initialize(requestContext);
No Error,but not check session value.
how to solve this.
Posted
Comments
Raul Iloc 23-Mar-14 15:37pm    
Did you try my solution?

1 solution

1.If you are trying to allow access only to authorized users, the management of unauthorized access to site functionalities should be done by using the [Authorize] attribute. So in all controllers' public actions that require authentication we must use this attribute, and in the controller class (or better in your base class for all controllers) you should manage the access like in the next code:
C#
protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is UnauthorizedAccessException)
    {
        //
        // Manage the Unauthorized Access exceptions
        // by redirecting the user to Home page.
        //
        filterContext.ExceptionHandled = true;
        filterContext.Result = RedirectToAction("LogIn", "Account");
    }
    //
    base.OnException(filterContext);
}


2.If you want to have control over the controller action before to execute the current action, you could do it by overriding the next controller members:

C#
/// <summary>
        /// Disable the Async support.
        /// </summary>
        /// <remarks>
        /// Must be disable, otherwise ExecuteCore() will not be invoked in MVC4 like was in MVC3!
        /// </remarks>
        protected override bool DisableAsyncSupport
        {
            get { return true; }
        }

protected override void ExecuteCore()
        {
            
//
// Your code for accessing the data from Session 
//
//...

            //
            // Invokes the action in the current controller context.
            //
            base.ExecuteCore();
        }
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900