Easiest way to parse “querystring” formatted data

不问归期 提交于 2019-11-26 11:24:41

问题


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\"].


回答1:


Pretty easy... Use the HttpUtility.ParseQueryString method.

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.



回答2:


You can do it with linq like this.

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.ParseQueryString then it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.




回答3:


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();



回答4:


If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.

Note that you have to convert the response body to a valid Uri so that ParseQueryString works.

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.

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();



回答5:


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;
}



回答6:


System.Net.Http ParseQueryString extension method worked for me. I'm using OData query options and trying to parse out some custom parameters.

options.Request.RequestUri.ParseQueryString();

Seems to give me what I need.



来源:https://stackoverflow.com/questions/11956948/easiest-way-to-parse-querystring-formatted-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!