Asp.net mvc controller 中如何正确存取cookie

2024年11月16日 16:23
有2个网友回答
网友(1):

给你一个完整的例子,看了后自然明白怎么回事了。

public class CookieController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        string cookie = "There is no cookie!";
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
        }
        ViewData["Cookie"] = cookie;
        return View();
    }
 
    public ActionResult Create()
    {
        HttpCookie cookie = new HttpCookie("Cookie");
        cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        return RedirectToAction("Index", "Home");
    }
 
    public ActionResult Remove()
    {
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
            cookie.Expires = DateTime.Now.AddDays(-1);
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        }
        return RedirectToAction("Index", "Home");
    }
}

网友(2):

HttpContext.Current.Request.Cookies["cook"];