Problem getting cookie from code-behind (worked in code-beside)

A

Alan Silver

Hello,

I am just converting one of my pages from code-beside to code-behind. I
removed all the C# and put that in a separate file (Basket.cs) and added
references for all the ASP controls on the page. I changed the Page
references to "using" and added a class around the code.

When I tried to run the page, I got an error when I tried to reference
Request.Cookies. I remembered form a previous time that you have to use
HttpContext.Current to get at the Request object, so I added that.
Trouble is, it now gives me an error "Object reference not set to an
instance of an object" on the line that tries to get the cookie value.

I have shown a very simplified version of the .cs file below. Anyone any
idea what the problem is? The DisplayBasket method is called when the
page first loads, and it is the first line of this that causes the
problem. I have snipped the rest for clarity.

Thanks for any help.



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ... a few others

public class Basket : Page {

protected Literal litSiteName; // plus a whole load more

void DisplayBasket() {
int basketId = Convert.ToInt32(HttpContext.Current.Request.Cookies["BasketID"].Value);
// do other stuff
}
}
 
A

Alan Silver

int basketId =
Convert.ToInt32(HttpContext.Current.Request.Cookies["BasketID"].Value);
</snip>

I should mention that I know the cookie exists. I've been using it for a
couple of days when the code was in the same file. The problem has only
arisen now I've moved the code to a separate file.

I know I should check to see if the cookie exists first, but that isn't
the problem in this case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top