Reputation: 4848
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.QueryString["aspxerrorpath"]
and it works fine.
But if a user directly accesses that page the it will generate an exception because aspxerrorpath
is not there.
How can I check that aspxerrorpath
is there or not?
Upvotes: 90
Views: 212895
Reputation: 1
//Use Haskeys() And GetKey(0)
if (Request.QueryString.HasKeys() && Request.QueryString.GetKey(0) == "aspxerrorpath")
{
//It has a key and the key is valid
string KeyValueByIndex = Request.QueryString[0];
//OR
string KeyValueByName = Request.QueryString["aspxerrorpath"];
}
else
{
//else...
}
Upvotes: 0
Reputation: 351
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.
Upvotes: 20
Reputation: 31
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.
Upvotes: 3
Reputation: 51124
What about a more direct approach?
if (Request.QueryString.AllKeys.Contains("mykey")
Upvotes: 6
Reputation: 499392
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.
Upvotes: 42
Reputation: 2346
You can also try:
if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
return;
Upvotes: 12
Reputation: 7438
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.
Upvotes: 2
Reputation: 161012
You can just check for null
:
if(Request.QueryString["aspxerrorpath"]!=null)
{
//your code that depends on aspxerrorpath here
}
Upvotes: 144
Reputation: 27944
string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value
Will return if there is a value
Upvotes: 10