Mohammad Esmaeili
Mohammad Esmaeili

Reputation: 155

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?

Upvotes: 7

Views: 12768

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

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()

Upvotes: 12

McKabue
McKabue

Reputation: 2232

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

Upvotes: 6

Related Questions