在Asp.Net Mvc 4中使用Cookie

48

我有一个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");
    }

我在_Layout中使用此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的最佳方法是什么?


你为什么不使用表单身份验证? - GvM
我该如何使用它?我知道这个,但不是很深入,所以我无法使用表单身份验证。我有一些特殊的流程,我担心无法使用表单身份验证完成它们。 - Elvin Mammadov
3个回答

71
尝试使用 Response.SetCookie(),因为 Response.Cookies.Add() 可能会导致添加多个cookie,而 SetCookie 会更新已有的cookie。

谢谢您的回复,但它再次无效。请观看这个链接:http://screencast.com/t/eMeFnm6Hq - Elvin Mammadov
非常奇怪,为什么我的LogOut操作没有被断点处理?!但是RedirectToActionParmenently却正常工作 :( - Elvin Mammadov
那么,只有在使用RedirectToAction()时才会出现问题? - GvM
谢谢!Response.SetCookie()确实有帮助。 - Rohan Rao

15

我们正在使用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.

2
userCookie.Expires.AddDays(365); 

这行代码没有任何作用。它相当于:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

您可能需要的是:
userCookie.Expires = DateTime.Now.AddDays(365); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接