Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a query string in a C# Windows Store App (a.k.a. WinRT/Metro)?

I want to access a web resource with an HTTP GET query string, ex.:

http://stackoverflow.com/search?q=search%20example&tab=relevance

In a regular .NET Framework 4.5 application, you can use System.Net.WebClient.QueryString:

Remarks

The QueryString property contains a NameValueCollection instance containing name/value pairs that are appended to the URI as a query string. The contents of the QueryString property are preceded by a question mark (?), and name/value pairs are separated from one another by an ampersand (&).

For Store Apps, you can even parse them with Windows.Foundation.WwwFormUrlDecoder.

But for creating a query string, the best snippet I could find in MSDN was this:

UriBuilder baseUri = new UriBuilder("http://www.contoso.com/default.aspx?Param1=7890");
string queryToAppend = "param2=1234";

if (baseUri.Query != null && baseUri.Query.Length > 1)
    baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; 
else
    baseUri.Query = queryToAppend; 

(from: http://msdn.microsoft.com/en-us/library/system.uribuilder.query(v=vs.110).aspx)

Is Microsoft really implying I should join my parameters with "=" and "&" myself? Isn't there a better way?

like image 799
divieira Avatar asked Nov 11 '22 14:11

divieira


1 Answers

Currently, there isn't one available that I'm aware of.

It's easy enough to create something that mirrors the original .NET functionality:

public static class UriExtensions
{
    public static Uri CreateUriWithQuery(Uri uri, NameValueCollection values)
    {
        var queryStr = new StringBuilder();
        // presumes that if there's a Query set, it starts with a ?
        var str = string.IsNullOrWhiteSpace(uri.Query) ?
                  "" : uri.Query.Substring(1) + "&";

        foreach (var value in values)
        {
            queryStr.Append(str + value.Key + "=" + value.Value);
            str = "&";
        }
        // query string will be encoded by building a new Uri instance
        // clobbers the existing Query if it exists
        return new UriBuilder(uri)
        {
            Query = queryStr.ToString()
        }.Uri;
    }
}

public class NameValueCollection : Dictionary<string, string> 
{
}

Using like:

var uri = UriExtensions.CreateUriWithQuery(new Uri("http://example.com"), 
    new NameValueCollection { { "key1", "value1" }, { "key2", "value2" }});

Results:

http://localhost/?key1=value1&key2=value2
like image 93
WiredPrairie Avatar answered Nov 14 '22 21:11

WiredPrairie