Sarawut Positwinyu
Sarawut Positwinyu

Reputation: 5042

Cookie does not work in asp.net

I have two pages, test1.aspx and test2.aspx

test1.aspx has this

protected void Page_Load(object sender, EventArgs e)
{
  HttpCookie cookie = new HttpCookie("test", "test");
  cookie.Expires = DateTime.Now.AddDays(1);
  Response.SetCookie(cookie);
}

test2.aspx has this

protected void Page_Load(object sender, EventArgs e)
{
  Response.Write(Response.Cookies["test"].Value);
}

The value of the cookie is null, no matter how many times I tried. I tried to open page1 and then page 2, expecting a cookie to work, but it is not working, I don't know why.

Upvotes: 3

Views: 10440

Answers (5)

Chris Moutray
Chris Moutray

Reputation: 18349

I think you need to read off the Request instead of the response.

As MSDN suggestions

protected void Page_Load(object sender, EventArgs e) 
{
    Response.Write(Request.Cookies["test"].Value);
}

In a web application, the request comes from the client (browser) and the response is sent from the server. When validating cookies or cookie data from the browser you should use the Request.Cookies collection. When you are constructing cookies to be sent to the browser you need to add them to the Response.Cookies collection.

Additional thoughts on the use of SetCookie

Interestingly for HttpResponse.SetCookie as used on your first page; MSDN says this method is not intended for use in your code.

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Even the example code found on this page uses the Response.Cookies.Add(MyCookie) approach and does not call SetCookie

Upvotes: 8

Prince Waleed
Prince Waleed

Reputation: 195

Save cookie with (response) and read cookie by (request)

//write
response.cookies("abc") = 123;

//read
if ((request.cookies("abc") != null)) {
string abc = request.cookies("abc");
}

Upvotes: 2

Prashant Mehta
Prashant Mehta

Reputation: 482

On page test2.aspx

You should try this

    protected void Page_Load(object sender, EventArgs e)
    {
        var httpCookie = Request.Cookies["test"];
        if (httpCookie != null) 
        {
            Response.Write(httpCookie.Value);
        }
    }

Upvotes: 0

Steve
Steve

Reputation: 121

Use Response.Cookies.Add(cookie);

Reference: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies

Upvotes: 1

BizApps
BizApps

Reputation: 6130

You need is :

protected void Page_Load(object sender, EventArgs e) 
{
    Response.Write(Request.Cookies["test"].Value);
}

There is a sample here: Reading and Writing Cookies in ASP.NET and C#

Regards

Upvotes: 2

Related Questions