C# 在 Asp.Net Mvc 4 中使用 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19128507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:10:03  来源:igfitidea点击:

Using Cookie in Asp.Net Mvc 4

c#asp.net-mvc-4cookiesactionhttpcookie

提问by Elvin Mammadov

I have web application in Asp.Net MVC4and I want to use cookiefor user's login and logout. So my actions as follows:

我在Asp.Net MVC4 中有 Web 应用程序,我想使用cookie进行用户登录和注销。所以我的操作如下:

Login Action

登录操作

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

And I use this cookie in _Loyout as follow:

我在 _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>
  }

But When I click*UserOut* action this action happen first time, but then it doesn't work. I put breakpoint for looking process but it get UserLogaction doesn't UserOut. My question is that where I use wrong way of cookie? What is a best way using cookie in Asp.Net Mvc4for this scenario ?

但是当我单击*UserOut* 操作时,此操作第一次发生,但随后不起作用。我为查找过程设置了断点,但它得到UserLog操作不是UserOut。我的问题是我在哪里使用了错误的 cookie 方式?对于这种情况,在Asp.Net Mvc4 中使用 cookie 的最佳方法是什么?

采纳答案by GvM

Try using Response.SetCookie(), because Response.Cookies.Add()can cause multiple cookies to be added, whereas SetCookiewill update an existing cookie.

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

回答by Anil Singh

We are using Response.SetCookie()for update the old one cookies and Response.Cookies.Add()are use to add the new cookies. Here below code CompanyIdis update in old cookie[OldCookieName].

我们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.

回答by Jonathan Allen

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

这行代码没有做任何事情。它相当于:

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

You probably want

你可能想要

userCookie.Expires = DateTime.Now.AddDays(365);