C# 解析“查询字符串”格式数据的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11956948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way to parse "querystring" formatted data
提问by Tom Gullen
With the following code:
使用以下代码:
string q = "userID=16555&gameID=60&score=4542.122&time=343114";
What would be the easiest way to parse the values, preferably without writing my own parser? I'm looking for something with the same functionality as Request.querystring["gameID"].
解析值的最简单方法是什么,最好不要编写自己的解析器?我正在寻找与Request.querystring["gameID"].
回答by Chris Shain
Pretty easy... Use the HttpUtility.ParseQueryString method.
很简单...使用HttpUtility.ParseQueryString 方法。
Untested, but this should work:
未经测试,但这应该有效:
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.
回答by Adil
You can do it with linq like this.
你可以像这样用 linq 做到这一点。
string query = "id=3123123&userId=44423&format=json";
Dictionary<string,string> dicQueryString =
query.Split('&')
.ToDictionary(c => c.Split('=')[0],
c => Uri.UnescapeDataString(c.Split('=')[1]));
string userId = dicQueryString["userID"];
Edit
编辑
If you can use HttpUtility.ParseQueryStringthen it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.
如果您可以使用HttpUtility.ParseQueryString ,那么它将更加直接,并且不会像 LinQ 那样区分大小写。
回答by erdomke
As has been mentioned in each of the previous answers, if you are in a context where you can add a dependency to the System.Web library, using HttpUtility.ParseQueryStringmakes sense. (For reference, the relevant source can be found in the Microsoft Reference Source). However, if this is not possible, I would like to propose the following modification to Adil'sanswer which accounts for many of the concerns addressed in the comments (such as case sensitivity and duplicate keys):
正如在前面的每个答案中都提到的那样,如果您处于可以向 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();
回答by Amadeus Sánchez
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uriextension method ParseQueryStringfound in System.Net.Http.
如果你想避免需要使用上的System.Web依赖HttpUtility.ParseQueryString,您可以使用Uri扩展方法ParseQueryString中发现的System.Net.Http。
Note that you have to convert the response body to a valid Uriso that ParseQueryStringworks.
请注意,您必须将响应正文转换为有效的,Uri以便ParseQueryString工作。
Please also note in the MSDN document, this method is an extension method for the Uri class, so you need reference the assembly System.Net.Http.Formatting (in System.Net.Http.Formatting.dll). I tried installed it by the nuget package with the name "System.Net.Http.Formatting", and it works fine.
还请注意MSDN文档中,该方法是Uri类的扩展方法,因此需要引用程序集System.Net.Http.Formatting(在System.Net.Http.Formatting.dll中)。我尝试通过名为“System.Net.Http.Formatting”的 nuget 包安装它,它工作正常。
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
回答by penguin river
How is this
这怎么样
using System.Text.RegularExpressions;
// query example
// "name1=value1&name2=value2&name3=value3"
// "?name1=value1&name2=value2&name3=value3"
private Dictionary<string, string> ParseQuery(string query)
{
var dic = new Dictionary<string, string>();
var reg = new Regex("(?:[?&]|^)([^&]+)=([^&]*)");
var matches = reg.Matches(query);
foreach (Match match in matches) {
dic[match.Groups[1].Value] = Uri.UnescapeDataString(match.Groups[2].Value);
}
return dic;
}
回答by MrRobboto
System.Net.Http ParseQueryString extension method worked for me. I'm using OData query options and trying to parse out some custom parameters.
System.Net.Http ParseQueryString 扩展方法对我有用。我正在使用 OData 查询选项并尝试解析一些自定义参数。
options.Request.RequestUri.ParseQueryString();
Seems to give me what I need.
似乎给了我我需要的东西。

