【WinRT】获取 Uri 中的参数(QueryString)键值对

在控制台或者其它类型的项目中,可以添加 System.Web,使用以下代码来获取一个 Uri 中的参数

Uri uri = new Uri("http://www.cnblogs.com/h82258652/?gender=male&age=17");
NameValueCollection collection = HttpUtility.ParseQueryString(uri.Query);
for (int index = 0; index < collection.Count; index++)
{
    var name = collection.Keys[index];
    var value = collection[index];
}

那么就可以分别得到 gender 和 age。

PS:NameValueCollection 类有 Keys 和 AllKeys 两个比较容易令人糊涂的属性,stackoverflow 上有讲解:http://stackoverflow.com/questions/803484/what-is-the-difference-between-the-properties-keys-and-allkeys-on-a-namevaluecol

 

但是,上面的代码在 WinRT 中没法用了,因为 HttpUtility 这个类在 WinRT 中是不存在的。自己 Split 获取吧,也行,不过就是担心写错,还有 Url 解码那东西呢。能有轮子用的话,就没必要再去发明个轮子了,于是谷歌一下,终于找到了,于是就写篇 blog 记录下。

需要使用 WwwFormUrlDecoder 这个类。代码如下:

Uri uri = new Uri("http://www.cnblogs.com/h82258652/?gender=male&age=17");
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);
// 遍历。
foreach (var nameValue in decoder)
{
    var name = nameValue.Name;
    var value = nameValue.Value;
}
// 获取某一个的值。
var gender = decoder.GetFirstValueByName("gender");
posted @ 2015-06-16 21:24  h82258652  阅读(1321)  评论(0编辑  收藏  举报