2

I have my own HandleErrorAttribute, which reads data from Exception and HttpContext, insert them into template and send an e-mail to administrator. It usually works fine, but it some cases it breaks, when trying to check if QueryString is not empty.

var requestParams = "";
if (context.Request.QueryString != null && context.Request.QueryString.Keys.Count > 0)
{
    foreach (String key in context.Request.QueryString.Keys)
    {
        requestParams += key + ": " + context.Request.QueryString[key] + "<br />";
    }
}
else
{
    requestParams = "[ no query string data ]";
}

It breaks when checking condition (NullReferenceException), even if I can see in debug, that QueryString is not null and the Keys.Count is equal to 0.

What am I missing here? How to do a proper check for an empty QueryString?

Stacktrace:

w System.Web.Hosting.IIS7WorkerRequest.GetQueryStringPtr(Int32& length)
w System.Web.Hosting.IIS7WorkerRequest.GetQueryStringRawBytes()
w System.Web.HttpRequest.get_QueryStringBytes()
w System.Web.HttpRequest.FillInQueryStringCollection()
w System.Web.HttpRequest.EnsureQueryString()
w System.Web.HttpRequest.get_QueryString()
w System.Web.HttpRequestWrapper.get_QueryString()
w project.Infrastructure.Attributes.ErrorHandlingAttribute.BuildErrorEmail(Exception exc, HttpContextBase context) w c:\Users\Marcin Bigoraj\Documents\Visual Studio 2012\Projects\project\Infrastructure\Attributes\ErrorHandlingAttribute.cs:wiersz 141
w project.Infrastructure.Attributes.ErrorHandlingAttribute.<>c__DisplayClass2.<OnException>b__1() w c:\Users\Marcin Bigoraj\Documents\Visual Studio 2012\Projects\project\Infrastructure\Attributes\ErrorHandlingAttribute.cs:wiersz 182
w System.Threading.Tasks.Task.InnerInvoke()
w System.Threading.Tasks.Task.Execute()
2
  • Can you post the stacktrace? Commented Jul 11, 2014 at 11:22
  • I just tested this in a controller, and it works like a charm, without any exceptions. Could you post more related code? Maybe the whole attribute if possible? Commented Jul 11, 2014 at 12:02

2 Answers 2

7

Check this code

if (Request.QueryString.Keys.Count > 0)
{

}
Sign up to request clarification or add additional context in comments.

1 Comment

This is GREAT! checking to see if it's null wasn't working for me. +1
0

You can determine if there are any values in the QueryString by checking its count:

Request.QueryString.Count > 0;

It is sufficient.

3 Comments

-1 if the QueryString is null you will get an exception
Even with this I have the same exception.
@Șhȇkhaṝ sry I would but I cant: "your last answer was ... ago. Your vote is locked..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.