1

My session becomes null when I redirect to another controller's Action, what should I do?

2
  • Take a look at the accepted answer on this page: stackoverflow.com/questions/889516/…
    – Clayton
    Aug 7 '12 at 11:37
  • 1
    Clayton, the link that you provided are talking about override the "OnActionExecuting" method and access the session there, but I don't know how to do that, as I am new to MVC, could you help me with that
    – daisy
    Aug 7 '12 at 11:46
1

With regards to the comment you posted me, here is what I was thinking. In the Controller where you need the session use something similar to this:

//Controller A
public class TheController : Controller
{
   public ActionResult Index(){
     Session["yourSession"] = "Hello World";
     return View();
   }
}


//Controller B
public class MyController : Controller
{
    string textString;

    protected override void OnActionExecuting(ActionExecutingContext ctx)
    {
        base.OnActionExecuting(ctx);
        textString = ctx.HttpContext.Session["yourSession"].ToString();
    }

    public ActionResult Index(){
       string currentText = textString;
       return View();
    }
}

I tested the suggestion from (http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors), and the contents of the session were available.

11
  • And how do I set the session it?
    – daisy
    Aug 7 '12 at 12:05
  • could you clarify what you mean by "set the session", please? The Contents of the session are dynamic, so you can fill it at will. Just write - Session["myNewSessionVariable"] = "Hello World";
    – Clayton
    Aug 7 '12 at 12:08
  • I have a Controller A , in that I have a Post Method for Login, where I am trying to set the Session variable like this: System.Web.HttpContext.Current.Session["User"]=objUser, Now after Login, I have to redirect him to another controller's Action method, There I need tocheck, If(System.Web.HttpContext.Current.Session["User"]!=null), but here I am always getting it as NULL
    – daisy
    Aug 7 '12 at 12:13
  • Yes that's correct. From the OnActionExecuting method, which should be found in Controller B, just use the following - User user = (User)ctx.HttpContext.Session["User"]; The User object can be placed as a class variable so that you can access it from any Action method you like.
    – Clayton
    Aug 7 '12 at 12:17
  • Just to clarify, when I say "User Object", I'm actually referring to what you're placing in the Session.
    – Clayton
    Aug 7 '12 at 12:18
1

You have to create a unique base controller with a session property, then all controllers within your project will inherit from that BaseController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MonitoringCSP.Controllers
{
//[AllowAnonymous]
//[Authorize(Roles = "admin")]
public class BaseController : Controller
{
    private HttpSessionStateBase _session;
    protected HttpSessionStateBase CrossControllerSession
    {
        get
        {
            if (_session == null) _session = Session;
            return _session;
        }
        set {
                _session = Session;
            }
        }
    }
}

Usage sample

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.Security;
    using MonitoringCSP.Models;

    namespace MonitoringCSP.Controllers
    {
[AllowAnonymous]
public class AccountController : BaseController
{
    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
                /*session*/
                CrossControllerSession["UserName"] = User.Identity.Name;
                /*end session*/
        return RedirectToAction("someAction");
        }
   }
}
1

I realized that I was clearing and destroying all sessions prior to setting the new session on login like this

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Session.Abandon();
Session.Clear();

When I removed these lines, everything started working like @Clayton said, so I removed these lines and replaced it with Session.Remove('sessionvariablename'), I am still not sure what issue were the above lines causing, but my code started working.

1

Make sure your controller does not have this attribute set on it:

[SessionState(SessionStateBehavior.Disabled)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.