Convert C# URI/URL to Absolute or Relative

There are many situations when you handle URLs or URIs in applications today, no matter if it's a web-application or not. Often you need to handle absolute URLs, like https://testsite.com/section/page, and relative URLs, like /section/page.html.

To easily convert URLs between absolute and relative, or just ensure these two formats, I created extension-methods for the type System.Uri, which allows you to write code like this:

var absoluteToRelative = new Uri("https://www.test-relative.com/customers/details.html").ToRelative();
// Outputs: "/customers/details.html"

var relativeToAbsolute = new Uri("/orders/id-123/", UriKind.Relative).ToAbsolute("https://www.test-absolute.com");
// Outputs: "https://www.test-absolute.com/orders/id-123/"

The extension-methods which makes this possible are the following:

public static string ToRelative(this Uri uri)
{
    // TODO: Null-checks

    return uri.IsAbsoluteUri ? uri.PathAndQuery : uri.OriginalString;
}

public static string ToAbsolute(this Uri uri, string baseUrl)
{
    // TODO: Null-checks

    var baseUri = new Uri(baseUrl);

    return uri.ToAbsolute(baseUri);
}

public static string ToAbsolute(this Uri uri, Uri baseUri)
{
    // TODO: Null-checks

    var relative = uri.ToRelative();

    if (Uri.TryCreate(baseUri, relative, out var absolute))
    {
        return absolute.ToString();
    }

    return uri.IsAbsoluteUri ? uri.ToString() : null;
}
Comments