HttpUtility.ParseQueryString的可移植类库(PCL)版本

时间:2013-11-28 14:24:20

标签: c# asp.net .net portable-class-library system.web

System.Web中是否包含HttpUtility.ParseQueryString的可移植类库(PCL)版本或我可以使用的一些代码?我想阅读一个非常复杂的网址。

4 个答案:

答案 0 :(得分:23)

HttpUtility.ParseQueryString返回继承自HttpValueCollection的{​​{1}}(内部类)。 NameValueCollection是一个键值对的集合,如字典,但它支持重复,维护顺序,只实现NameValueCollection(此集合是预先泛型)。 PCL不支持IEnumerable

我的解决方案(部分解除并从.NET框架修改)是用NameValueCollection替换HttpValueCollection,其中Collection<HttpValue>只是一个键值对。

HttpValue

<强>更新

已更新,以便HttpValueCollection现在继承自Collection而非List,如评论中突出显示。

更新2

如果使用.NET 4.5,则更新为使用WebUtility.UrlDecode,感谢@Paya。

答案 1 :(得分:5)

你也可以像这样实现它:

public static class HttpUtility
{
    public static Dictionary<string, string> ParseQueryString(Uri uri)
    {
        var query = uri.Query.Substring(uri.Query.IndexOf('?') + 1); // +1 for skipping '?'
        var pairs = query.Split('&');
        return pairs
            .Select(o => o.Split('='))
            .Where(items => items.Count() == 2)
            .ToDictionary(pair => Uri.UnescapeDataString(pair[0]),
                pair => Uri.UnescapeDataString(pair[1]));
    }
}

以下是单元测试:

public class HttpParseQueryValuesTests
{
    [TestCase("http://www.example.com", 0, "", "")]
    [TestCase("http://www.example.com?query=value", 1, "query", "value")]
    public void When_parsing_http_query_then_should_have_these_values(string uri, int expectedParamCount,
        string expectedKey, string expectedValue)
    {
        var queryParams = HttpUtility.ParseQueryString(new Uri(uri));
        queryParams.Count.Should().Be(expectedParamCount);

        if (queryParams.Count > 0)
            queryParams[expectedKey].Should().Be(expectedValue);
    }
}

答案 2 :(得分:1)

我的Flurl库是一个PCL,当您从字符串中实例化IDictionary<string, object>对象时,它会将查询字符串解析为Url

using Flurl;

var url = new Url("http://...");
// get values from url.QueryParams dictionary

相关的解析逻辑是here。 Flurl很小,但如果你愿意,可以随意刷一下这些。

答案 3 :(得分:1)

我今天制作了一个nuget包,用于进行基本的查询构建和解析。它是为个人使用而制作的,但可从nuget.com repo获得。对于个人使用,意味着它可能不完全符合&#39; http查询规范&#39;。 Nuget link here

它基于字典,所以不支持重复键,主要是因为我不知道你为什么会这样......(任何人都能启发我吗?)

它有1个类,表示支持添加,获取参数,检查它是否包含密钥的查询...以及解析密钥并返回查询实例的静态方法。