Session variable still remains null between two di

2019-03-03 22:20发布

问题:

I have a problem with my MVC project! The goal is to set a session var in order to pass it to all the controllers: inside my xUserController,

            Session["UserId"] = 52;
            Session.Timeout = 30;

            string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : ""; 

//SessionUserId ="52"

But within the ChatMessageController

[HttpPost]
public ActionResult AddMessageToConference(int? id,ChatMessageModels _model){

        var response = new NzilameetingResponse();
        string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
//...

        }
        return Json(response, "text/json", JsonRequestBehavior.AllowGet);
}

SessionUserId = ""

So, Why this ? How to set the session variable to be global within all my controllers ??

回答1:

There can be only two reasons of such behavior: the first one is that your session is over and the second is that you rewrite you session variable from another place in your application. Wthout any additional code there is nothing to say more.



回答2:

Here is how I solved the issue

I know this is not the best way to do it but it helped me:

First I have created a base controller as follows

public class BaseController : Controller
{
    private static HttpSessionStateBase _mysession;
    internal protected static HttpSessionStateBase MySession {
        get { return _mysession; }
        set { _mysession = value; } 
    }
}

then I changed all my controllers' codes in other to let them inherit from the Base Controller class.

Then I overrode the "OnActionExecuting" method as below :

public class xUserController : BaseController
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        BaseController.MySession = Session;
        base.OnActionExecuting(filterContext);
    }
    [HttpPost]
    public ActionResult LogIn(FormCollection form)
    {
        //---KillFormerSession();
        var response = new NzilameetingResponse();
        Session["UserId"] = /*entity.Id_User*/_model.Id_User;
        return Json(response, "text/json", JsonRequestBehavior.AllowGet);
    }
}

Finally, I've changed the way I call session variables.

string SessionUserId = ((BaseController.MySession != null) && (BaseController.MySession["UserId"] != null)) ? BaseController.MySession["UserId"].ToString() : "";

instead of

 string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";

now it works and my session vars can walk across all controllers.