C # persistent cookie

I've seen examples of persistent cookies in ASP.NET MVC C # here on stackoverflow. But I cannot figure out why the below code is not 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 can see the cookies stored in Internet Explorer. The content looks fine.

Then the reading code:

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

      

The cookie variable is kept null. Failed to store PrinterSetting2 value in test variable.

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

+3


source to share


2 answers


try with below code: -

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

      

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



Following are several types for writing and reading cookies: -

Non-Persist Cookie - the cookie has an expired time called Non-Persist Cookie

How do I create a cookie? Its very easy to create a cookie in Asp.Net with a 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 get from a cookie?

     

Its an easy way to get the cookie of a form form using a 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();
    }

      

+1


source


You have to make sure you have values ​​in Request.QueryString. Just to check if your code works with hardcoded cookie values ​​and then read from cookie.



0


source







All Articles