How to check that Request.QueryString has a specific value or not in ASP.NET?

前端 未结 8 1273
孤街浪徒
孤街浪徒 2020-12-08 06:12

I have an error.aspx page. If a user comes to that page then it will fetch the error path in page_load() method URL using Request.QueryStrin

相关标签:
8条回答
  • 2020-12-08 06:24
    string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value
    

    Will return if there is a value

    0 讨论(0)
  • 2020-12-08 06:27

    think the check you're looking for is this:

    if(Request.QueryString["query"] != null) 
    

    It returns null because in that query string it has no value for that key.

    0 讨论(0)
  • 2020-12-08 06:33

    You can just check for null:

    if(Request.QueryString["aspxerrorpath"]!=null)
    {
       //your code that depends on aspxerrorpath here
    }
    
    0 讨论(0)
  • 2020-12-08 06:40

    To check for an empty QueryString you should use Request.QueryString.HasKeys property.

    To check if the key is present: Request.QueryString.AllKeys.Contains()

    Then you can get ist's Value and do any other check you want, such as isNullOrEmpty, etc.

    0 讨论(0)
  • 2020-12-08 06:44

    Check for the value of the parameter:

    // .NET < 4.0
    if (string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]))
    {
     // not there!
    }
    
    // .NET >= 4.0
    if (string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"]))
    {
     // not there!
    }
    

    If it does not exist, the value will be null, if it does exist, but has no value set it will be an empty string.

    I believe the above will suit your needs better than just a test for null, as an empty string is just as bad for your specific situation.

    0 讨论(0)
  • 2020-12-08 06:46

    To resolve your problem, write the following line on your page's Page_Load method.

    if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;
    

    .Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:

    if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;
    

    This will not run your next statements (your business logics) if query string does not have aspxerrorpath.

    0 讨论(0)
提交回复
热议问题