Accessing cookies in class file gives null reference exception

Posted by SheoNarayan under Error and Solution on 8/4/2011 | Points: 10 | Views : 7904 | Status : [Administrator] | Replies : 2

Sometimes you might need to access the Request.Cookies or other properties of the Request object in the Class library (asp.net) under App_Code folder. Sometimes even if your code is compiling properly, you will get error at the runtime.

eg. following code in the class library (inherited with System.Web.UI.MasterPage) compiles properly but throws error null reference exception in the run time.

if (Request.Cookies["CodeF"] != null)
{
string background = Request.Cookies["CodeF"]["BackImage"].ToString();
this.Page.Header.Controls.Add(new LiteralControl(background));
}


The solution

 if (HttpContext.Current.Request.Cookies["CodeF"] != null)
{
string background = HttpContext.Current.Request.Cookies["CodeF"]["BackImage"].ToString();
this.Page.Header.Controls.Add(new LiteralControl(background));
}


Use the HttpContext.Current.Request object and it will work as expected.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com



Responses

Posted by: Bugwee on: 8/4/2011 [Member] Starter | Points: 25

Up
0
Down
Hi Sir Sheo,

What is the difference between the two if will use the Request.* and HttpContext.Current.Request.* ?
why is it that null reference will be given if we just use the "Request.Cookies["something"]" object in the class library under app_code?


Thanks



SheoNarayan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Hmanjarawala on: 8/5/2011 [Member] Bronze | Points: 25

Up
0
Down
Hello sir,
As per my knowledge Request object and HttpContext.Current.Request Both are same.
am i right??

Himanshu Manjarawala
Sr. Software Engineer@AutomationAnywhere
http://fieredotnet.wordpress.com/

SheoNarayan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response