Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting/accessing QueryString values in ASP.NET

Tags:

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?

like image 470
Nick Avatar asked Mar 02 '09 23:03

Nick


2 Answers

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

        public int age {          get         {             if (Request.QueryString["Age"] == null)                 return 0;             else                 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.

like image 188
7wp Avatar answered Oct 07 '22 02:10

7wp


One thing is you're not capturing blank values here. You might have a url like "http://example.com?someKey=&anotherKey=12345" and in this case the "someKey" param value is "" (empty). You can use string.IsNullOrEmpty() to check for both null and empty states.

I'd also change "someKey" to be stored in a variable. That way you're not repeating literal strings in multiple places. It makes this easier to maintain.

int val = 0; string myKey = "someKey"; if (!string.IsNullOrEmpty(Request.QueryString[myKey])) {     val = int.Parse(Request.QueryString[myKey]); } 

I hope that helps!

Ian

like image 26
Ian Suttle Avatar answered Oct 07 '22 03:10

Ian Suttle