Where's the HttpUtility.ParseQueryString Metho

2019-03-19 06:37发布

问题:

Since HttpUtility is not available in WinRT, I was wondering if there's a straightforward way to parse HTTP query strings?

Is there actually some equivalent to HttpUtility.ParseQueryString in WinRT?

回答1:

Instead of HttpUtility.ParseQueryString you can use WwwFormUrlDecoder.

Here's an example I grabbed here

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