2017-02-10 85 views
0

因此,这里有一个想法。我有一个SessionCache类,它用于获取和设置简单用户信息的会话变量。因此,一旦用户成功登录,我想设置会话值并使用此类来获取整个应用程序的会话值。但不知何故,我无法将值设置为SessionCache类中的会话变量。使用mvc中的属性分配会话值

public class SessionCache 
{ 
    public static string SessionID 
    { 
     get 
     { 
      return HttpContext.Current.Session.SessionID; 
     } 
    } 
    public static CurrentUserVM CurrentUser 
    { 
     get 
     { 
      return (CurrentUserVM)HttpContext.Current.Session["CurrentUser"]; 
     } 
     set 
     { 
      HttpContext.Current.Session["CurrentUser"] = CurrentUser; 
     } 
    } 
} 

所以,我试着用下面登录操作上面的类来设定值:

CurrentUserVM currentUser = new CurrentUserVM(); 
currentUser.User = db.userClass.FirstOrDefault(m => m.EmailID.Equals(objLogin.EmailID)); 
currentUser.isAuthenticated = true; 
SessionCache.CurrentUser = currentUser; 
SessionCache.CurrentUser.isAuthenticated = currentUser.isAuthenticated; 

但仍保持SessionCache.CurrentUser null.Is有什么错我的代码?

+1

尝试'HttpContext.Current.Session [ “当前用户”] =值;' –

+1

这是一个非常糟糕的主意,不过,至少在数据你正在储存。诸如用户是否被认证之类的事情不应该存储在会话中。无论如何,这可以通过'User.Identity.IsAuthenticated'随时检索,所以真的没有理由。像用户的电子邮件地址等信息应始终来自数据库。检索用户记录的成本非常低,尤其是在Entity Framework使用自己的查询缓存之后,您不必记得始终更新会话中的内容。 –

+0

我完全同意你在那里说的任何内容。但是这并没有处理大量的数据,只是登录后将用户重定向到网站的不同部分。我在这里没有使用太多的用户数据。这个应用程序太简单了使用Identity.but谢谢反正@ ChrisPratt – Mash

回答

1

我觉得问题很明显。只是简单的改变这

HttpContext.Current.Session["CurrentUser"] = CurrentUser; 

这个

HttpContext.Current.Session["CurrentUser"] = value; 
+0

我甚至在想什么..谢谢。谢谢 – Mash

+0

@Mash,不客气,不要忘了标记这个答案,如果解决你的问题。谢谢 :) – jtabuloc