Click here to Skip to main content
15,867,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to like below but throwing an error "
Object reference not set to an instance of an object.
"

C#
string roll = Request.Cookies["StudentCookies"].Value;
            if (roll == null || roll == String.Empty)
            {
                Response.Redirect("~/LoginPage.aspx");
            }
Posted

Try:
C#
string roll = Request.Cookies["StudentCookies"] == null ? "" : Request.Cookies["StudentCookies"].Value;
 
Share this answer
 
Comments
dawood abbas 19-Jun-15 5:26am    
thanq but how to set null value to this coockie?
dawood abbas 19-Jun-15 5:26am    
in logout page i want to null it..
OriginalGriff 19-Jun-15 5:49am    
Response.Cookies["StudentCookies"].Value = null;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);

To be sure, to be sure, to be sure... :laugh:
You are trying to use Request.Cookies.Value without checking it the cookie exists.

This is the correct check:
C#
string roll = string.Empty;
// first check that cookie exists, if it does, use the value
if (Request.Cookies["StudentCookies"] != null) {
    roll = Request.Cookies["StudentCookies"].Value;
}

' if cookie wasn't present or the value is empty, redirect
if ( roll == string.empty)
    Response.Redirect("~/LoginPage.aspx");


Good luck.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900