Last active
November 16, 2017 08:43
-
-
Save sebnilsson/1e4663ed5577a350330e to your computer and use it in GitHub Desktop.
Get relative part of an Uri
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ToRelative(this Uri uri) | |
{ | |
if (uri == null) | |
{ | |
throw new ArgumentNullException(nameof(uri)); | |
} | |
return uri.IsAbsoluteUri ? uri.PathAndQuery : uri.OriginalString; | |
} | |
public static string ToAbsolute(this Uri uri, string baseUrl) | |
{ | |
if (uri == null) | |
{ | |
throw new ArgumentNullException(nameof(uri)); | |
} | |
if (baseUrl == null) | |
{ | |
throw new ArgumentNullException(nameof(baseUrl)); | |
} | |
var baseUri = new Uri(baseUrl); | |
return uri.ToAbsolute(baseUri); | |
} | |
public static string ToAbsolute(this Uri uri, Uri baseUri) | |
{ | |
if (uri == null) | |
{ | |
throw new ArgumentNullException(nameof(uri)); | |
} | |
if (baseUri == null) | |
{ | |
throw new ArgumentNullException(nameof(baseUri)); | |
} | |
var relative = uri.ToRelative(); | |
if (Uri.TryCreate(baseUri, relative, out var absolute)) | |
{ | |
return absolute.ToString(); | |
} | |
return uri.IsAbsoluteUri ? uri.ToString() : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment