48

I keep feeling like I'm reinventing the wheel, so I thought I'd ask the crowd here. Imagine I have a code snippet like this:

string protocol = "http"; // Pretend this value is retrieved from a config file
string host = "www.google.com"; // Pretend this value is retrieved from a config file
string path = "plans/worlddomination.html"; // Pretend this value is retrieved from a config file

I want to build the url "http://www.google.com/plans/worlddomination.html". I keep doing this by writing cheesy code like this:

protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;    
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);

What I really want is some sort of API like:

UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();

I gotta believe this exists in the .NET framework somewhere, but nowhere I've come across.

What's the best way to build foolproof (i.e. never malformed) urls?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Mike
  • 5,560
  • 12
  • 41
  • 52
  • Read Alex Black's answer, then Click Here: http://social.msdn.microsoft.com/Search/en-US/?Refinement=27%2c117&Query=Uri+Builder – John Saunders Jul 16 '09 at 00:59

2 Answers2

50

Check out the UriBuilder class

waterlooalex
  • 13,642
  • 16
  • 78
  • 99
50

UriBuilder is great for dealing with the bits at the front of the URL (like protocol), but offers nothing on the querystring side. Flurl [disclosure: I'm the author] attempts to fill that gap with some fluent goodness:

using Flurl;

var url = "http://www.some-api.com"
    .AppendPathSegment("endpoint")
    .SetQueryParams(new {
        api_key = ConfigurationManager.AppSettings["SomeApiKey"],
        max_results = 20,
        q = "Don't worry, I'll get encoded!"
    });

There's a new companion library that extends the fluent chain with HTTP client calls and includes some nifty testing features. The full package is available on NuGet:

PM> Install-Package Flurl.Http

or just the stand-alone URL builder:

PM> Install-Package Flurl

Todd Menier
  • 37,557
  • 17
  • 150
  • 173