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

I have an error.aspx page. If the user comes to this page, he will look for the error path in the page_load() URL method using Request.QueryString["aspxerrorpath"] , and it works fine.

But if the user directly accesses this page, he will throw an exception because aspxerrorpath does not exist.

How can I check if aspxerrorpath is there or not?

+46
Dec 30 '11 at 10:26
source share
8 answers

You can just check for null :

 if(Request.QueryString["aspxerrorpath"]!=null) { //your code that depends on aspxerrorpath here } 
+81
Dec 30 '11 at 10:28
source share

Check the parameter value:

 // .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 exists but does not matter, it will be an empty string.

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

+33
Dec 30 '11 at 10:28
source share

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

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

Then you can get the ist value and do any other check like isNullOrEmpty, etc.

+8
Jun 04 '14 at 12:22
source share
 string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value 

Will return if there is a value

+7
Dec 30 '11 at 10:28
source share

You can also try:

 if (!Request.QueryString.AllKeys.Contains("aspxerrorpath")) return; 
+6
Feb 18 '14 at 9:21
source share

How about a more direct approach?

 if (Request.QueryString.AllKeys.Contains("mykey") 
+2
Nov 05 '15 at 9:42 on
source share

To fix the problem, write the following line on the Page_Load page.

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

.Net 4.0 looks at null, empty, or white space in more detail, use it as shown in the following line:

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

This will not trigger your next statements (your business logic) if the query string does not have an aspxerrorpath.

+1
Dec 30 '11 at 10:43
source share

I think the check you are looking for is this:

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

It returns null because in this query string it does not matter for this key.

+1
Dec 17 '15 at 8:45
source share



All Articles