2013-04-25 77 views
0

我的MVC项目存在问题!我们的目标是建立一个会话变种,以便将它传递给所有控制器: 我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

会话varialbe是全球唯一 – Devesh 2013-04-25 09:34:47

+0

当然,但你怎么解释SessionUserId =“”在其他控制器?我必须写什么? – Bellash 2013-04-25 09:41:18

+0

您使用哪种浏览器? – Sharun 2013-04-25 09:59:06

回答

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() : ""; 

现在的作品和我的会话增值经销商可以在所有控制器行走。

0

这种行为可能只有两个原因:第一个原因是您的会话已结束,第二个原因是您从应用程序中的其他位置重写了会话变量。没有任何额外的代码,没有什么可说的。

+0

不!请看我的答案,我是如何解决它的 – Bellash 2013-04-25 13:07:53

相关问题