Session变量仍然是两个不同的控制器之间的空 [英] Session variable still remains null between two different controllers
问题描述
我有一个问题,我的MVC项目!的目标是建立一个会话变种,以便将它传递给所有控制器:
我xUserController里面,
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
//SessionUserId ="52"
但ChatMessageController内
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 =
SessionUserId = ""
那么,为什么这样?如何设置会话变量是我的所有控制器??
So, Why this ? How to set the session variable to be global within all my controllers ??
推荐答案
下面是我如何解决这个问题。
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; }
}
}
然后,我改变了我的所有控制器'codeS在其他让他们从基础类继承。
then I changed all my controllers' codes in other to let them inherit from the Base Controller class.
然后我重写了OnActionExecuting的方法如下:
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() : "";
而不是
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
现在的作品,我的会话增值经销商可以在所有控制器走路。
now it works and my session vars can walk across all controllers.
这篇关于Session变量仍然是两个不同的控制器之间的空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!