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

2024-11-16 16:23:20
推荐回答(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"];