在Asp.Net Mvc 4中使用Cookie

Elv*_*dov 47 c# cookies action httpcookie asp.net-mvc-4

我在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");
    }
Run Code Online (Sandbox Code Playgroud)

LogOut Action

    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");
    }
Run Code Online (Sandbox Code Playgroud)

我在_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>
  }
Run Code Online (Sandbox Code Playgroud)

但是当我点击*UserOut*动作时,这个动作第一次发生,但是它不起作用.我把断点用于查找进程,但它得到的UserLog操作不是UserOut.我的问题是我在哪里使用错误的cookie方式?在这种情况下,在Asp.Net Mvc4中使用cookie的最佳方法是什么?

GvM*_*GvM 71

尝试使用Response.SetCookie(),因为Response.Cookies.Add()可以导致添加多个cookie,而SetCookie将更新现有的cookie.


Ani*_*ngh 14

我们使用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.
Run Code Online (Sandbox Code Playgroud)