HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Using RouteValueDictionary to convert anonymous type to query string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertanonymousquerytyperoutevaluedictionaryusingstring

Problem

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;
}

Solution

Instead of catching an exception if the url is relative, use the System.Uri class to see if it is an absolute Uri.

Context

StackExchange Code Review Q#3063, answer score: 2

Revisions (0)

No revisions yet.