简体   繁体   中英

How can read / write cookie in C# & ASP.NET MVC

I have problem with cookies, this is my read and write code in the class:

public static class language
{
   public static void set_default(string name)
   {
       HttpContext.Current.Response.Cookies.Remove("language");
       HttpCookie language = new HttpCookie("language");
       language["name"] = name;
       language.Expires = DateTime.Now.AddDays(1d);
       HttpContext.Current.Response.Cookies.Add(language);
   }

   public static string get_default()
   {
       string name = string.Empty;
       HttpCookie langauge = HttpContext.Current.Response.Cookies.Get("language");
       name = langauge["name"];
       return name;
   }
}

When I go to the next page and use @language.get_default() to get the default language, the response is null - why?

When writing cookies, you add cookies to Response . when Reading them you should use Request :

HttpCookie language = HttpContext.Current.Request.Cookies.Get("language");

So the set_default() is correct, but you should make change to get_default()

am not sure language.Expires = DateTime.Now.AddDays(1d); is correct. DateTime.Now.AddDays accepts an integer and 1d is not.

CREATE COOKIE:

HttpContext.Response.Cookies.Append("language", "ENGLISH", new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(5)
            });

GET COOKIE:

 string language = HttpContext.Request.Cookies["language"];

DELETE COOKIE:

HttpContext.Response.Cookies.Append("language", "", new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(-1)
            });

or

HttpContext.Response.Cookies.Delete("language");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM