如何在asp.net mvc视图之间共享变量
我需要从所有asp.net mvc应用程序中访问UserId,以便使用它隐藏/显示某些元素: 用户ID是SQL server中用户表中的主键 在普通asp.net中,我使用了BasePage:Page并添加了:如何在asp.net mvc视图之间共享变量,asp.net,asp.net-mvc-2,Asp.net,Asp.net Mvc 2,我需要从所有asp.net mvc应用程序中访问UserId,以便使用它隐藏/显示某些元素: 用户ID是SQL server中用户表中的主键 在普通asp.net中,我使用了BasePage:Page并添加了: public long FinKaynUserId { //long FinKaynUserId = 0; get { if (HttpContext.Current.Session["FinKaynUserId"] != null &&
public long FinKaynUserId
{
//long FinKaynUserId = 0;
get
{
if (HttpContext.Current.Session["FinKaynUserId"] != null && Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]) != 0)
return Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]);
else
{
HttpCookie myCookie = HttpContext.Current.Request.Cookies["FinKaynUserId"];
if (myCookie != null)
{
HttpContext.Current.Session["FinKaynUserId"] = Convert.ToInt64(myCookie.Value);
// Session["User"] = (new UserManager()).GetUser(Convert.ToInt64(Session["UserId"]));
return Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]);
}
else
return 0;
}
}
set
{
HttpCookie cookie = new HttpCookie("FinKaynUserId");
cookie.Value = value.ToString();
cookie.Secure = false;
cookie.Expires = DateTime.Now.AddDays(3);
HttpContext.Current.Request.Cookies.Add(cookie);
HttpContext.Current.Session["FinKaynUserId"] = value;
}
}
如何在asp.net mvc中执行相同的操作。一个选项是将变量存储在应用程序上下文中:
Application["FinKaynUserId"] = value;
然后您可以在其他代码部分获得它,如下所示:
if (Application["FinKaynUserId"] != null)
{
long FinKaynUserId = (long)Application["FinKaynUserId"];
}
HttpContext.Current.Session[Session\u User]=值 如果变量使用在会话级别,则使用:会话[变量]=值;
或者,如果在整个应用程序中使用,则使用:System.Web.HttpContext.Current.application[Variable]=value 我想在视图之间共享一个用户ID。如果会话已过期,请检查Cookie。下面是另一篇与MVC相关的文章,其中包含MVC特定的指导原则:您仍然可以在asp.net MVC应用程序中使用会话变量,但是我建议使用内置的asp.net FormsAuthentication,而不是自己管理会话和cookies。FormsAuthentication在cookie中存储用户名。用户名在sql server的“我的用户”表中不是唯一的。我必须使用用户名或电子邮件。用户通过电子邮件进行身份验证,Pass==>Get UserId==>在所有视图中使用。FormsAuthentication是否可以这样做?您不必将真实用户名用作FormsAuthentication票证,您可以告诉FormsAuthentication存储您喜欢的任何内容,例如用户的电子邮件地址或用户ID,然后使用user.Identity.name检索存储的票证密钥应用程序变量是全局变量,在所有请求中共享,所以它不是存储用户id的好地方。请使用会话变量,而不是标题的会话变量。不是应用程序变量。@user594166我的评论是关于Stas答案和应用程序的用法[FinKaynUserId]