在Asp.Net Mvc中使用Cookie

我有Asp.Net MVC4中的 Web应用程序,我想使用Cookie进行用户login和注销。 所以我的行为如下:

login操作

[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"); } 

LogOut操作

  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。

我们正在使用Response.SetCookie()来更新旧的Cookie和Response.Cookies.Add()来添加新的Cookie。 下面的代码中,CompanyId是旧的Cookie [OldCookieName]中的更新。

 HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name. cookie.Values["CompanyID"] = Convert.ToString(CompanyId); Response.SetCookie(cookie); //SetCookie() is used for update the cookie. Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.