Get Object Reference Error when trying to use Request.QueryString

This question already has an answer here:

  • What is a NullReferenceException, and how do I fix it? 33 answers

  • 你需要检查空值

    if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
    {
       //Do something
    }
    

    You can do this:

    if(Request.QueryString.Length != 0)
    {
       ...
    }
    

    If you try to access elements which are not present, you'll receive an exception. So, since QueryString has a property of Length , checking it against 0 means there is no query string at all.

    Else if you want to know that only if id key isn't present, you can do this:

    if(Request.QueryString.AllKeys.Contains("id"))
    {
    
    }
    

    Try this:

    if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
    {
     //Do something
    }
    

    Another way :

    string id = Request.QueryString["id"] ?? "";
    if(id == "1")
    {
         //Do something
    }
    
    链接地址: http://www.djcxy.com/p/28040.html

    上一篇: C#NullReferenceException未被用户代码处理

    下一篇: 尝试使用Request.QueryString时获取对象引用错误