我在Asp.Net MVC4中有Web应用程序,并且我想使用cookie来进行用户的登录和注销。所以我的动作如下:
登录动作
[HttpPost]
public ActionResult Login(string username, string pass)
{
if (ModelState.IsValid)
{
var newUser = _userRepository.GetUserByNameAndPassword(username, pass);
if (newUser != null)
{
var json = JsonConvert.SerializeObject(newUser);
var userCookie = new HttpCookie("user", json);
userCookie.Expires.AddDays(365);
HttpContext.Response.Cookies.Add(userCookie);
return RedirectToActionPermanent("Index");
}
}
return View("UserLog");
}
注销操作
public ActionResult UserOut()
{
if (Request.Cookies["user"] != null)
{
var user = new HttpCookie("user")
{
Expires = DateTime.Now.AddDays(-1),
Value = null
};
Response.Cookies.Add(user);
}
return RedirectToActionPermanent("UserLog");
}
我在_Loyout中使用此cookie,如下所示:
@using EShop.Core
@using Newtonsoft.Json
@{
var userInCookie = Request.Cookies["user"];
}
...
@if (userInCookie != null && userInCookie.Value)
{
<li><a href="#">Salam</a></li>
<li><a href="@Url.Action("UserOut", "Home")">Cıxış</a></li>
}
else
{
<li><a href="@Url.Action("UserLog", "Home")">Giriş</a></li>
}
但是,当我单击* UserOut *操作时,此操作是第一次发生,但是随后不起作用。我将断点用于查看进程,但它得到的UserLog操作不是UserOut。我的问题是,我在哪里使用错误的Cookie方式?在这种情况下,在Asp.Net Mvc4中使用cookie的最佳方法是什么?
尝试使用Response.SetCookie()
,因为Response.Cookies.Add()
可能会导致添加多个cookie,而SetCookie
会更新现有的cookie。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句