Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;
}
share|improve this question

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.