在我的登录页面中,我有这样的登录代码......
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
但是,当我在Signin之后立即检查User.Identity时,它仍然是未经身份验证的
this.User.Identity.IsAuthenticated
返回false。
我遗失的任何东西?
答案 0 :(得分:1)
在下一个请求之前,this.User.Identity.IsAuthenticated不成立。在我的情况下,我重定向到主页/索引。进入HomeController.Index()方法后,我看到IsAuthenticated == true。
从这里开始:http://msdn.microsoft.com/en-us/library/twk5762b.aspx
表单身份验证票证将表单身份验证信息提供给浏览器发出的下一个请求。
答案 1 :(得分:0)
我假设你正在使用ASP.NET身份。这是一个工作模板,看看你的代码有什么不同。
型号:
public class LoginViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
控制器:
//
// GET: /My/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /My/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid account name or password.");
}
}
return View(model);
}
页:
@using (Html.BeginForm("Login", "My", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
@Html.ValidationSummary(false)
<div class="form-group">
<p class="col-md-2 control-label"><strong>Account</strong></p>
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" /> | @Html.ActionLink("Cancel", "Index", "Explore")
</div>
</div>
}