I don't have the Request, I only have a url string. Also, the url can either be relative or absolute. And since Uri and UriBuilder do not support relative urls, I'll probably have to do it manually, unless there is a trick I'm not aware of. This method will be used in probably more than a thousand lines of code in my project that's why I'd like to do it right.
The following code will break if a relative url is passed:
public static string AddQueryStringIfNotExists(string url, string parameter, string value)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query[parameter] == null)
{
query[parameter] = value;
uriBuilder.Query = query.ToString();
}
return uriBuilder.ToString();
}
P.S. I'm fine with doing it manually by checking whether my parameter appears after the first ? but that would require tackling several edge cases, the thing I'm trying to avoid (like a parameter name contained in another parameter)