Wednesday, January 02, 2008
A more useful UrlBuilder class

When I started my first ASP.NET project in 05, my URL building code included way too many string concatenations, String.Format calls and plain literals.

Being pre-MS-MVC days of typed URL construction via routing engines, I needed some code to make URL construction (particularly the query string) easier.

Then I found this UrlBuilder class. This is a great little class because it neatly derives from the framework UriBuilder class.

Since I started using it, I found it was inadequate when dealing with case sensitive HTTP servers. The specialized StringDictionary it uses lower-cases all keys and values.

To suit my needs, I modified the class in a few ways:

  • Upgraded to C# 3 - I think I'm addicted to lambda's so I involuntarily compiled it in .NET framework 3.5
  • The un-rendered query string is now stored as Dictionary<string,string> instead of StringDictionary which avoids casing problems
  • Provided overloads for ToString() casing - upper,lower or default (leaves casing alone)

Here's a simple example for building a Clickatell SMS sending URL.


UrlBuilder builder = new UrlBuilder("http://api.clickatell.com/http/sendmsg");
builder.QueryString["api_id"] = "23223";
builder.QueryString["user"] = "cutnpaste";
builder.QueryString["password"] = "ninja";
builder.QueryString["to"] = "61043678945";
builder.QueryString["text"] = "the message to send";
Console.WriteLine(builder.ToString(StringCaseDirection.Lower));


Download source code

kick it on DotNetKicks.com

Tags: , , ,

posted @ Wednesday, January 02, 2008 4:33 AM | Feedback (2)
Posts
8
Comments
28
Trackbacks
0