我仔细阅读了下面的answer,我认为它应该有效,但是在这个评论的哪个部分和哪个部分?
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, isPersistent);
if (!isPersistent)
{
//this is because if it was not set then it got
//automatically set to expire next year even if
//the cookie was not set as persistent
authCookie.Expires = DateTime.Now.AddMinutes(15);
}
Response.Cookies.Add(authCookie);
是在global.asax还是Controller本身?
以下是我的代码。
来自控制器视图:
[HttpPost]
public ActionResult Login(User user, string returnUrl)
{
if (ModelState.IsValid)
{
var username = user.Username;
var getPassword = (from item in db.User
where item.Username == username
select new UserModel()
{
Password = item.Password
}
).SingleOrDefault();
if (getPassword != null)
{
var hashingPass = Models.PasswordHash.ValidatePassword(user.Password, getPassword.Password);
var getAdmin = (from item in db.User
where item.Username == username && hashingPass == true
select new UserModel()
{
UserId = item.UserId
}
).ToList();
if (getAdmin.Count.Equals(1))
{
FormsAuthentication.SetAuthCookie(username, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index");
}
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
return View(user);
}
来自HTML视图:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<form role="form">
<fieldset>
<div class="form-group">
<label for="Username">Username</label>
<input class="form-control" placeholder="Enter Username" name="Username" id="Username" type="text" autofocus oninput="setCustomValidity('')" required/>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input class="form-control" placeholder="Enter Password" name="Password" id="Password" type="password" value="" oninput="setCustomValidity('')" required>
</div>
<button type="submit" style="background-color:#f7aa52; border:1px solid #f78952; color:#fff;" class="btn btn-lg btn-block">Login</button>
</fieldset>
</form>
}
答案 0 :(得分:0)
它在控制器级别。
您也可以在
下的 web.config 中指定Cookie到期日期server