Walt501
Walt501

Reputation: 73

C# persistent cookie

I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow. But I can't figure out why the code below isn't working.

First I write to the cookie:

HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);

cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);

Response.Cookies.Add(cookie);

I see the cookies stored in Internet Explorer. The content looks OK.

Then the reading code:

HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();

The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.

I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?

Upvotes: 3

Views: 4470

Answers (2)

Neel
Neel

Reputation: 11721

try with below code :-

if (Request.Cookies["AdminPrintModule"] != null)
{
    HttpCookie cookie = Request.Cookies["AdminPrintModule"];
    test = cookie["PrinterSetting2"].ToString();
}

Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-

Below are few types to write and read cookies :-

Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie? Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie

Example 1:

    HttpCookie userInfo = new HttpCookie("userInfo");
    userInfo["UserName"] = "Annathurai";
    userInfo["UserColor"] = "Black";
    userInfo.Expires.Add(new TimeSpan(0, 1, 0));
    Response.Cookies.Add(userInfo);

Example 2:

    Response.Cookies["userName"].Value = "Annathurai";
    Response.Cookies["userColor"].Value = "Black";

How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object. Example 1:

    string User_Name = string.Empty;
    string User_Color = string.Empty;
    User_Name = Request.Cookies["userName"].Value;
    User_Color = Request.Cookies["userColor"].Value;

Example 2:

    string User_name = string.Empty;
    string User_color = string.Empty;
    HttpCookie reqCookies = Request.Cookies["userInfo"];
    if (reqCookies != null)
    {
        User_name = reqCookies["UserName"].ToString();
        User_color = reqCookies["UserColor"].ToString();
    }

Upvotes: 1

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.

Upvotes: 0

Related Questions