我的MVC项目有问题!目标是设置会话var以将其传递给所有控制器: 在我的xUserController中,
Session["UserId"] = 52;
Session.Timeout = 30;
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
// SessionUserId =“52”
但在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 =“”
那么,为什么呢?如何在我的所有控制器中将会话变量设置为全局?
答案 0 :(得分:0)
这种行为只有两个原因:第一个是你的会话结束,第二个是你从应用程序的另一个地方重写会话变量。 没有任何额外的代码,没有什么可说的。
答案 1 :(得分:0)
以下是我解决问题的方法
我知道这不是最好的方法,但它帮助了我:
首先,我创建了一个基本控制器,如下所示
public class BaseController : Controller
{
private static HttpSessionStateBase _mysession;
internal protected static HttpSessionStateBase MySession {
get { return _mysession; }
set { _mysession = value; }
}
}
然后我在其他地方更改了所有控制器的代码,让它们从Base Controller类继承。
然后我覆盖了“OnActionExecuting”方法,如下所示:
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);
}
}
最后,我改变了调用会话变量的方式。
string SessionUserId = ((BaseController.MySession != null) && (BaseController.MySession["UserId"] != null)) ? BaseController.MySession["UserId"].ToString() : "";
而不是
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
现在它可以工作,我的会话变量可以遍历所有控制器。