I am trying to take advantage of the reflection built into RouteValueDictionary to add values to the query string of a URL. This is what I came up with. It seems to work, but I thought I would post it to see if anyone has any suggestions. It also uses the super-secret HttpValueCollection returned by ParseQueryString(), which automatically generates a URL-encoded query string.
So far the only negative is that it only works on URLs that can be parsed by UriBuilder (i.e. absolute URLs). So, relative URLs (i.e. "/Home/Index") will throw an exception. Maybe I should try the UriBuilder, and if that fails then try to extract/append the query string manually.
public static string AppendQueryValues(this string absoluteUrl, object queryValues)
{
if (absoluteUrl == null)
throw new ArgumentNullException("absoluteUrl");
if (queryValues == null)
throw new ArgumentNullException("queryValues");
// Parse URL so we can modify the query string
var uriBuilder = new UriBuilder(absoluteUrl);
// Parse query string into an HttpValueCollection
var queryItems = HttpUtility.ParseQueryString(uriBuilder.Query);
// Parse & filter queryValues (using reflection) into key/value pairs
var newQueryItems = new RouteValueDictionary(queryValues)
.Where(x => !queryItems.AllKeys.Contains(x.Key));
// Add new items to original collection
foreach (var newQueryItem in newQueryItems)
{
queryItems.Add(newQueryItem.Key, newQueryItem.Value.ToString());
}
// Save new query string (HttpValueCollection automatically URL encodes)
uriBuilder.Query = queryItems.ToString();
return uriBuilder.Uri.AbsoluteUri;
}
1 Answer 1
Instead of catching an exception if the url is relative, use the System.Uri class to see if it is an absolute Uri.