Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Mohammad Esmaeili Avatar asked Jul 29 '18 06:07

Mohammad Esmaeili


People also ask

What is cookie in C?

Cookies are small units of information that follow all request processes and web pages as they travel between Web browsers and servers. The above definition implies that every web page opened on a website has an exchange of cookies between the server and the web pages.

What is cookie What is use of it how do you read and write cookie object?

Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.


2 Answers

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

like image 194
Ashkan Mobayen Khiabani Avatar answered Sep 22 '22 19:09

Ashkan Mobayen Khiabani


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");
like image 31
McKabue Avatar answered Sep 26 '22 19:09

McKabue