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?
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With