我制作了一个网站,其中的页面包含剃须刀表单。用户可以在此表单上登录,然后重定向到不同的页面。登录(和注销)成功地与表单验证一起工作。但是,我似乎无法使用 HttpContext.Current.User.Identity.Name 来检索存储的用户名(在表单身份验证 cookie 中)。它返回一个空字符串“”。
我正在使用没有标准成员资格或角色提供者的 MVC 5 和 ASP 4.5。
登录:
[HttpPost]
public ActionResult Login(User user)
{
if (ModelState.IsValid)
{
bool authenticated = userscontroller.isAuthorized(user.Email, user.Password);
if (authenticated)
{
if (userscontroller.isAuthenticated())
{
userscontroller.deAuthenticateUser();
}
userscontroller.authenticateUser(user);
return Redirect(Url.Action("Index", "Home"));
}
}
}
验证用户:
public void authenticateUser(User user)
{
FormsAuthentication.SetAuthCookie(user.Username, false);
}
然后获取用户名:
public User userFromCookie()
{
if (isAuthenticated())
{
return getUserByUsername(HttpContext.Current.User.Identity.Name);
}
else { return null; }
}
经过身份验证()
public bool isAuthenticated()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
return true;
}
else
{
return false;
}
}
网络配置:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization > <deny users="?"/> </authorization>
所以identity.name 返回“”。
帮助表示赞赏!