1

i m developing a website and stuck with System.NullReferenceException . on the master page I m using this code

if (Request.Url.ToString().ToLower().Contains("content.aspx"))
{
    if (Request.Params["ModuleID"].ToString() == null)
    {
        Response.Redirect("Content.aspx?ModuleID=1");
    }
}

when Module Id is blank then it creates null reference exception.

1
  • 1
    You already said where the error is. When ModuleID is blank (i.e. doesn't exist), Params["ModuleID"] returns null. Commented Apr 8, 2011 at 7:06

2 Answers 2

8

Just take out the call to ToString():

if (Request.Params["ModuleID"] == null)
{
    Response.Redirect("Content.aspx?ModuleID=1");
}

Currently you're trying to call ToString on a null reference.

This won't redirect if the ModuleID is present but empty though. You may want:

if (string.IsNullOrEmpty(Request.Params["ModuleID"]))
{
    Response.Redirect("Content.aspx?ModuleID=1");
}
Sign up to request clarification or add additional context in comments.

Comments

2

You have to check the Request.Params["ModuleID"] on null. An null does not have a .ToString(), that is why you get this exception. If you use the following code you should not get an NullReferenceException.

if (Request.Url.ToString().ToLower().Contains("content.aspx")) 
{ 
    if (Request.Params["ModuleID"] == null) 
    { 
        Response.Redirect("Content.aspx?ModuleID=1"); 
    } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.