从MVC中的全局变量访问值

时间:2014-06-26 06:05:34

标签: asp.net-mvc asp.net-mvc-4

您好我们使用mvc4和jquery mobile开发Web应用程序。在我们的每个控制器中,我们创建了如下的用户会话。

public class HomeController:BaseController {     private static User CurrentUser;

    public ActionResult Index(string name)
    {
       CurrentUser = (User)Session["CurrentUserSession"];
       return View();
    }

   public ActionResult UserDetaiks()
    {
       string username = CurrentUser.UserFName;
       return View()
     }

}

            Above we created object for User model and assigned session value in index method. But the value in CurrentUser is lost once i entered UserDetails. So i Used static while creating object. My question is it correct? or anyother way is there. Please guide me.

谢谢你们再一次怀疑,

我在表单身份验证中使用了以下代码。

 HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie != null)
                {

                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                    var s = new System.Web.Script.Serialization.JavaScriptSerializer();
                    User obj = s.Deserialize<User>(authTicket.UserData);

                    UserInformation CurrentUser = new UserInformation(obj.UserID);
                    CurrentUser.UserId = obj.UserID;
                    CurrentUser.FirstName = obj.UserFName;
                    CurrentUser.LastName = obj.UserLName;
                    CurrentUser.roles = obj.SecurityGroupName;
                    CurrentUser.DefaultWarehouseId = obj.DefaultWhseIdentity; eg:14
                    HttpContext.Current.User = CurrentUser;

                }



**Here User can Change CurrentUser.DefaultWarehouseId  later like CurrentUser.DefaultWarehouseId = 16. but when i leave the method. It again getting value 14. Now i can code so CurrentUser.DefaultWarehouseId will be 16 through out app one i changed, Please guide me.**

4 个答案:

答案 0 :(得分:1)

由于无法保证在UserDetails方法之前调用索引方法,因此我不会使用静态变量来存储用户。相反,每个控制器方法都应该根据需要从会话中获取用户。

答案 1 :(得分:1)

在我看来,这个问题更适合CodeReview,但我们走了:

您的代码要求用户首先访问Index以为您当前的用户变量分配值。如果用户首先访问详细信息,您将获得NullReferencEception

最后,如果您在每种方法中都不需要它,那么最好关闭ActionMethod中的当前用户。如果您在每个操作中都需要,可以在构造函数中初始化它

public class HomeController : BaseController
{
    public ActionResult Index(string name)
    {
       User CurrentUser = (User)Session["CurrentUserSession"];
       return View();
    }

    public ActionResult UserDetails()
    {
        User CurrentUser = (User)Session["CurrentUserSession"];
        string username = CurrentUser.UserFName;
        return View()
    }
 }

OR:

public class HomeController : BaseController
{
    private static User CurrentUser;
    public HomeController()
    {
         CurrentUser = (User)Session["CurrentUserSession"];
    }
    /* ... */
}

在任何情况下,您都应该检查Session变量是否为空。我想如果没有用户登录,这可能会变得很讨厌。

答案 2 :(得分:0)

在构造函数中初始化:

public class HomeController : BaseController
{
    private User CurrentUser;

    public HomeController()
    {
        CurrentUser = Session["CurrentUserSession"] as User;
    }

    public ActionResult Index(string name)
    {       
       return View();
    }

    public ActionResult UserDetaiks()
    {
        string username = CurrentUser.UserFName;
        return View()
     }
 }

答案 3 :(得分:0)

封装逻辑geting当前用户的另一种方法 - 使用自定义 ModelBinder 例如:

public class UserBinders : System.Web.Mvc.IModelBinder
{
       private const string SessionKey = "CurrentUser";

       public object BindModel(ControllerContext controllercontext, System.Web.Mvc.ModelBindingContext bindingContext)
       {  
          HttpContextWrapper httpcontext = new HttpContextWrapper(System.Web.HttpContext.Current);
          string userLogin = httpcontext.User.Identity.Name

          var currentUser = (User)controllercontext.HttpContext.Session[SessionKey];
          if (currentUser == null)
          {
              currentUser = context.GetUserByLogin(userLogin);
              controllercontext.HttpContext.Session[SessionKey] = currentUser;
          }

          return currentUser;
       }
}

只需声明变量类型用户并获取当前用户。

public ActionResult UserDetaiks(User CurrentUser)
{
   string username = CurrentUser.UserFName;
   return View()
 }