简体   繁体   中英

fix System.NullReferenceException in C#

im 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.

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");
}

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"); 
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM