Parsing URI query strings in Windows 8 metro-style apps

Tuesday, August 21, 2012


Take the URL string http://example.com/?a=foo&b=bar&c=baz. How do we parse its query parameters using C# to get a dictionary or other key-value data structure?

In .NET, you can use HttpUtility.ParseQueryString(), but that function isn't present in WinRT APIs. Fortunately, there is a replacement: WwwFormUrlDecoder. The code below demonstrates its capabilities:

using System;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Windows.Foundation;

[TestClass]
public class Tests
{
    [TestMethod]
    public void TestWwwFormUrlDecoder()
    {
        Uri uri = new Uri("http://example.com/?a=foo&b=bar&c=baz");
        WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);

        // named parameters
        Assert.AreEqual("foo", decoder.GetFirstValueByName("a"));

        // named parameter that doesn't exist
        Assert.ThrowsException<ArgumentException>(() => {
            decoder.GetFirstValueByName("not_present");
        });

        // number of parameters
        Assert.AreEqual(3, decoder.Count);

        // ordered parameters
        Assert.AreEqual("b", decoder[1].Name);
        Assert.AreEqual("bar", decoder[1].Value);

        // ordered parameter that doesn't exist
        Assert.ThrowsException<ArgumentException>(() => {
            IWwwFormUrlDecoderEntry notPresent = decoder[3];
        });
    }
}

Tags: metro, winrt, csharp | Posted at 15:36 | Comments (0)


Comments

There are no comments.

Add a comment

Name:
Email: (optional, not displayed to public)
URL:

Comment: