Live Fast, Code Hard, Die Young

If you’ve used the System.Uri class in .NET you may have stumbled upon the need to extract the base part of the URL and found no obvious solution. You know, you have a URL that looks like this:

http://www.mydomain.com/somepath/somepage.aspx?param=x

And you want to get only this part:

http://www.mydomain.com

If you put the long URL in a Uri object you would expect to be able to get the domain name part via a simple property but as you look through the class you won’t find it. There is a property called Authority for getting “www.mydomain.com” but then you need to concatenate that with the Scheme property which contains “http” and add “://” in between them to get a valid URL. Looks quite cumbersome to me.

I seem to hit this problem every once in a while and I keep forgetting how to do it properly. To me this indicates that the class is missing something obvious. Actually it has a method for getting what I want, and it is called GetLeftPart().

The GetLeftPart() method takes a UriPartial enum that describes how much of the URL to return. If we pass “Authority” to it we get what we want!

Interesting solution
Now I wouldn’t have blogged about this if the GetLeftPart() method was the end of it all. What I really wanted was an easy way to access the base URL and ideally that would be via a property. To achieve this we can create our own class that derives from Uri and add the property there.

Another interesting solution that I found is to add an extension method to the Uri class. Unfortunately there are no extension properties (yet) so we will have to settle for a method called GetBaseUrl(). Here is some code to do it:

namespace System
{
    public static class Extensions {
        public static string GetBaseUrl(this Uri uri)
        {
            return uri.GetLeftPart(UriPartial.Authority);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: