c# - 在 Asp.Net Mvc 4 中使用 Cookie

标签 c# asp.net-mvc-4 cookies action httpcookie

我在 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。

关于c# - 在 Asp.Net Mvc 4 中使用 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19128507/

相关文章:

c# - 无法确定条件表达式的类型

c# - 在单独的 js 文件中访问 Web 配置

c# - Web Api响应版本控制解决方案?

c# - 带有 ViewModel 和两个表单的页面上的 "The anti-forgery cookie token and form field token do not match"

ssl - 本地主机和主机上的 cookie

c# - 未解析响应中的 HttpWebRequest 和 Set-Cookie header (WP7)

c# - 异步等待返回任务

c# - 使用自定义设计器扩展 Visual Studio

c# - 无法在mvc4项目中添加 "Public"区域

php - 在图像加载时保存 cookie