34

I want to register the parameter of a few pages in my web site using cookie. I tried the below code but not like what I want :

 public ActionResult Index(int? dep, int? cat)
 {
   ......
   string theDept = Request.QueryString["dep"];
   HttpCookie cookie = new HttpCookie("search");
   cookie.Values["dep_name"] = theDept;
   cookie.Expires = DateTime.Now.AddDays(1);
   Response.Cookies.Add(cookie);
   return View();
 }

I read it in site.master :

<% 

HttpCookie cookie = Request.Cookies["search"] ;

if ((cookie != null) && (cookie.Value != ""))
{
    Response.Write(cookie.Values["dep_name"].ToString() + "---" +   
    cookie.Values["cat_name"].ToString() + "---" + cookie.Values["brand"].ToString());
}
%>

Problem: When I click to another page that Request.QueryString["dep"] is null, the cookie that I display is null to.

How to store it in the cookie without losing while we not yet clear the cookie?

Irf
  • 4,285
  • 3
  • 36
  • 49
titi
  • 1,025
  • 5
  • 16
  • 31

2 Answers2

74

I m not sure I understand if this is a question about how to properly send cookies to the client or some bug with your querystring params. So I ll post the proper way of sending cookies and feel free to correct me if I misunderstood.

In any case though, I believe this:

HttpCookie cookie = new HttpCookie("search");

will reset the search cookie

To get a cookie:

HttpCookie cookie = HttpContext.Request.Cookies.Get("some_cookie_name");

To check for a cookie's existence:

HttpContext.Request.Cookies["some_cookie_name"] != null

To save a cookie:

HttpCookie cookie = new HttpCookie("some_cookie_name");
HttpContext.Response.Cookies.Remove("some_cookie_name");
HttpContext.Response.SetCookie(cookie );
DeepSpace101
  • 13,110
  • 9
  • 77
  • 127
Yannis
  • 6,047
  • 5
  • 43
  • 62
  • I've been doing web stuff for nearly six years and I was given a task involving setting a cookie for the first time just recently. Weird, wild stuff. This helps, thanks! – MrBoJangles May 14 '14 at 19:40
  • 6
    To clarify, where would you put this code inside the MVC project to avoid filling up your controllers with trash? – Felipe Correa May 13 '15 at 15:14
  • doesn't the line `HttpContext.Response.Cookies.Remove` removes the cookie not saving it? – Jaylen Mar 23 '17 at 20:31
18

i have organised the cookie fetching and inserting in an organized manner such that it can be used throughout the application. for that purpose i put two methods SetCookie and GetCookie.

You can simply put this class in your code and work out.

Here i put my class with the static methods

public class CookieStore
{
    public static void SetCookie(string key, string value, TimeSpan expires)
    {
        HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));

        if (HttpContext.Current.Request.Cookies[key] != null)
        {
            var cookieOld = HttpContext.Current.Request.Cookies[key];
            cookieOld.Expires = DateTime.Now.Add(expires);
            cookieOld.Value = encodedCookie.Value;
            HttpContext.Current.Response.Cookies.Add(cookieOld);
        }
        else
        {
            encodedCookie.Expires = DateTime.Now.Add(expires);
            HttpContext.Current.Response.Cookies.Add(encodedCookie);
        }
     }
    public static string GetCookie(string key)
    {
        string value = string.Empty;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            // For security purpose, we need to encrypt the value.
            HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
            value = decodedCookie.Value;
        }
        return value;
    }

}

using these you can easily store values in cookie and fetch value whenever required

using these methods is as simple as

For Setting Cookie:

CookieStore.SetCookie("currency", "GBP", TimeSpan.FromDays(1)); // here 1 is no of days for cookie to live

For Getting Cookie:

string currency= CookieStore.GetCookie("currency");
Brian Low
  • 11,605
  • 4
  • 58
  • 63
Shiva Saurabh
  • 1,281
  • 2
  • 25
  • 47
  • When saving, why update the existing cookie instead of setting a new one? – Brian Low Jan 31 '14 at 18:30
  • 1
    i got an issue that i find the cookie twice when seen in quick watch one with expiry date as jan 1 0001, so thought to update it. – Shiva Saurabh Jan 31 '14 at 18:33
  • Are you using HttpSecureCookie from http://www.nuget.org/packages/httpsecurecookie/ ? – Brian Low Jan 31 '14 at 18:37
  • no its a customized class which i have used with machine key cryptography. you can perform cookie saving without encoding and decoding here. – Shiva Saurabh Jan 31 '14 at 18:52
  • i used this help for using HttpSecureCookie http://www.codeproject.com/KB/web-security/HttpSecureCookie.aspx. You can use the same – Shiva Saurabh Jan 31 '14 at 19:13
  • Could not find HttpSecureCookie. That's not kind business to those new to using this because they will waste time looking for it when it doesn't exist. Please make sure that is plain to the users. Don't assume everyone's coming in with full knowledge of the libraries – Clarence Mar 14 '19 at 21:03