C# ASP.NET MVC 4 Websecurity.CurrentUserId返回-1
我在ASP.NETMVC4项目中使用SimpleMembership。登录后,我无法获取当前用户名和当前用户名,以下是我的登录功能:C# ASP.NET MVC 4 Websecurity.CurrentUserId返回-1,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我在ASP.NETMVC4项目中使用SimpleMembership。登录后,我无法获取当前用户名和当前用户名,以下是我的登录功能: [HttpPost] public ActionResult Login(FormCollection form) { bool success = WebSecurity.Login(form["username"], form["password"], false); if (su
[HttpPost]
public ActionResult Login(FormCollection form)
{
bool success = WebSecurity.Login(form["username"], form["password"], false);
if (success)
{
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
{
Response.Redirect("~/home/index?userId=" + WebSecurity.CurrentUserId + "&userName=" + WebSecurity.currentUserName);
}
else
{
Response.Redirect(returnUrl);
}
}
return View();
}
在这一行Response.Redirect(“~/home/index?userId=“+WebSecurity.CurrentUserId+”&userName=“+WebSecurity.currentUserName”)代码>
WebSecurity.CurrentUserId
返回-1
和WebSecurity.currentUserName
返回”
我错过什么了吗?任何帮助都将不胜感激
但是,在我看来,如果我这样做{int value;value=WebSecurity.currentUserID;}{ViewBag.Title=value;}
浏览器中的标题就是正确的currentUserIDMSDN:
当用户登录时,ASP.NET会在
允许ASP.NET在后续请求中知道用户拥有的cookie
已登录。如果persistCookie为false,则令牌仅有效
直到用户关闭浏览器
因此,它只能用于登录后的请求。使用:
WebSecurity.GetUserId(username);
试试这个
[HttpPost]
public ActionResult Login(FormCollection form)
{
bool success = WebSecurity.Login(form["username"], form["password"], false);
if (success)
{
var userId = WebSecurity.GetUserId(form["username"]);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
{
Response.Redirect("~/home/index?userId=" + userId + "&userName=" + WebSecurity.currentUserName);
}
else
{
Response.Redirect(returnUrl);
}
}
return View();
}
在重定向完成(按设计)之前,Web安全性不会内部化。一种解决方法是在成功登录时通过用户名获取用户名为什么需要将这些项目添加到url?什么是LoginModel?当我添加它时,我得到了一个名称空间错误。我的答案适用于MVC ASP.net。让我给你更新一下