32

使用以下代码:

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

解析值的最简单方法是什么,最好不编写我自己的解析器?我正在寻找与Request.querystring["gameID"].

4

6 回答 6

83

很简单...使用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.
于 2012-08-14T16:43:34.270 回答
22

你可以像这样使用 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"];

编辑

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

于 2012-08-14T16:51:43.563 回答
7

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.ParseQueryString makes 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's answer which accounts for many of the concerns addressed in the comments (such as case sensitivity and duplicate keys):

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();
于 2017-02-01T13:40:36.730 回答
5

如果您想避免使用HttpUtility.ParseQueryString所需的对 System.Web 的依赖,您可以Uri使用.ParseQueryStringSystem.Net.Http

请注意,您必须将响应正文转换为有效的Uri,这样才能ParseQueryString正常工作。

另请注意,在 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();
于 2017-08-16T14:30:18.940 回答
4

这怎么样

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;
}
于 2018-11-05T11:22:12.373 回答
1

System.Net.Http ParseQueryString 扩展方法对我有用。我正在使用 OData 查询选项并尝试解析一些自定义参数。

options.Request.RequestUri.ParseQueryString();

似乎给了我我需要的东西。

于 2019-08-04T22:04:28.673 回答