Last active
November 7, 2019 22:00
-
-
Save flakey-bit/fb1eef64b8f9633da1b74c7226b233fe to your computer and use it in GitHub Desktop.
Build request URI with query parameters from base Uri and suffix (.NET) - encodes URI components
This file contains hidden or 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 Uri ComposeRequestUri(string baseUri, string pathSuffix=null, IDictionary<string, object> queryParameters=null) | |
{ | |
if (string.IsNullOrEmpty(baseUri)) | |
{ | |
throw new ArgumentException($"{nameof(baseUri)} is required", nameof(baseUri)); | |
} | |
var uri = new Uri(baseUri); | |
if (!string.IsNullOrEmpty(pathSuffix)) | |
{ | |
if (pathSuffix.StartsWith("/")) | |
{ | |
throw new ArgumentException($"{nameof(pathSuffix)} must be relative"); | |
} | |
uri = new Uri(uri, pathSuffix); | |
} | |
var uriBuilder = new UriBuilder(uri); | |
if (uriBuilder.Uri.IsDefaultPort) | |
{ | |
uriBuilder.Port = -1; // Omit port in Uri if it's the default port for the scheme | |
} | |
if (queryParameters != null) | |
{ | |
var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query); | |
foreach (var pair in queryParameters) | |
{ | |
query[pair.Key] = pair.Value.ToString(); | |
} | |
uriBuilder.Query = query.ToString(); | |
} | |
return uriBuilder.Uri; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment