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?
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.
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.
string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value
Will return if there is a value
What about a more direct approach?
if (Request.QueryString.AllKeys.Contains("mykey")
You can also try:
if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
return;
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.
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.
Source: Stackoverflow.com