Skip to content

Instantly share code, notes, and snippets.

@brunossn
Created May 8, 2019 20:51
Show Gist options
  • Save brunossn/1e81d6c53d849bddc16f2585a4f42b92 to your computer and use it in GitHub Desktop.
Save brunossn/1e81d6c53d849bddc16f2585a4f42b92 to your computer and use it in GitHub Desktop.
An C# auxiliary class to easily create URLs with parameters
public class UrlFactory
{
private Dictionary<string, string> _parameters;
private string _url;
public UrlFactory(string url)
{
_url = url;
_parameters = new Dictionary<string, string>();
}
public void AddParameter(string key, string value)
{
_parameters.Add(key, value);
}
public string GetFullUrl()
{
var url = _url;
if (_parameters.Count == 0)
return url;
var urlParameters = _parameters.Select(parameter => {
var key = WebUtility.UrlEncode(parameter.Key);
var value = WebUtility.UrlEncode(parameter.Value);
return $"{key}={value}";
});
return $"{url}?{string.Join("&", urlParameters)}";
}
}
@brunossn
Copy link
Author

brunossn commented May 8, 2019

Usage example:

var url = new UrlFactory("www.myapi.com/customer");
url.AddParameter("name", "Mr. Potato");
url.AddParameter("age", "32");

Console.WriteLine(url.GetFullUrl());
// www.myapi.com/customer?name=Mr.%20Potato&age=32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment