Csharp/C#教程:解析“查询字符串”格式化数据的最简单方法分享


解析“查询字符串”格式化数据的最简单方法

使用以下代码:

string q = "userID=16555&gameID=60&score=4542.122&time=343114"; 

什么是最简单的解析值的方法,最好不要编写我自己的解析器? 我正在寻找具有与Request.querystring["gameID"]相同function的东西。

非常简单…使用HttpUtility.ParseQueryString方法 。

未经测试,但这应该工作:

 var qs = "userID=16555&gameID=60&score=4542.122&time=343114"; var parsed = HttpUtility.ParseQueryString(qs); var userId = parsed["userID"]; // ^^^^^^ Should be "16555". Note this will be a string of course. 

你可以像这样使用linq。

 string query = "id=3123123&userId=44423&format=json"; Dictionary dicQueryString = query.Split('&') .ToDictionary(c => c.Split('=')[0], c => Uri.UnescapeDataString(c.Split('=')[1])); string userId = dicQueryString["userID"]; 

编辑

如果你可以使用HttpUtility.ParseQueryString那么它将更加直接,它不会像LinQ那样区分大小写。

正如前面每个答案中所提到的,如果您处于可以向System.Web库添加依赖项的上下文中,则使用HttpUtility.ParseQueryString是有意义的。 (作为参考,相关源可以在Microsoft参考源中找到 )。 但是,如果无法做到这一点,我想对Adil的答案提出以下修改,该答案解释了评论中提到的许多问题(例如区分大小写和重复密钥):

 var q = "userID=16555&gameID=60&score=4542.122&time=343114"; var parsed = q.TrimStart('?') .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(k => k.Split('=')) .Where(k => k.Length == 2) .ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1]) , StringComparer.OrdinalIgnoreCase); var userId = parsed["userID"].FirstOrDefault(); var time = parsed["TIME"].Select(v => (int?)int.Parse(v)).FirstOrDefault(); 

如果要避免使用HttpUtility.ParseQueryString所需的System.Web依赖,可以使用System.Net.HttpUri扩展方法ParseQueryString

请注意,您必须将响应主体转换为有效的Uri以便ParseQueryString工作。

另请注意,在MSDN文档中,此方法是Uri类的扩展方法,因此您需要引用程序集System.Net.Http.Formatting(在System.Net.Http.Formatting.dll中)。 我尝试使用名为“System.Net.Http.Formatting”的nuget包安装它,它工作正常。

上述就是C#学习教程:解析“查询字符串”格式化数据的最简单方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 string body = "value1=randomvalue1&value2=randomValue2"; // "https://localhost/query?" is added to the string "body" in order to create a valid Uri. string urlBody = "https://localhost/query?" + body; NameValueCollection coll = new Uri(urlBody).ParseQueryString(); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1004908.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐