Nick Nick - 1 year ago 55
ASP.NET (C#) Question

Converting/accessing QueryString values in ASP.NET

I'm curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:

int val = 0;
if(Request.QueryString["someKey"] != null)
val = Convert.ToInt32(Request.QueryString["someKey"]);

What are some better ways to handle this grossness?

7wp 7wp
Answer Source

I tend to like the idea of abstracting them as properties. For example:

        public int age { 
            if (Request.QueryString["Age"] == null)
                return 0;
                return int.Parse(Request.QueryString["Age"]);                                    

You could add more validation if you wanted to. But I tend to like wrapping all of my query string variables this way.

EDIT: --- Also as another poster pointed out that you have to create these properties on every page. My answer is no you do not. You can create these properties in a single class that you can call "QueryStrings" or something. Then you can instantiate this class in every page where you want to access your query strings, then you can simply do something like

var queryStrings = new QueryStrings();
var age = queryStrings.age;

This way you can encapsulate all of the logic for accessing and handling each type of query variable in a single maintainable location.

EDIT2: --- And because it is an instance of the class, you could also use dependency injection to inject the QueryStrings class in every place you are using it. StructureMap does a good job of that. This also allows you to mock up the QueryStrings class and inject that if you wanted to do automated unit testing. It is much easier to mock this up than ASP.Net's Request object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download