3

我使用 Stream reader 阅读context.Request.InputStream到最后并最终得到一个看起来像的字符串

"Gamestart=true&GamePlayer=8&CurrentDay=Monday&..."

在 C# 控制台中解析它的最有效/“干净”的方法是什么?

4

3 回答 3

9

您可以使用HttpUtility.ParseQueryString

小样本:

string queryString = "Gamestart=true&GamePlayer=8&CurrentDay=Monday"; //Hardcoded just for example
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

foreach (String k in qscoll.AllKeys)
{
    //Prints result in output window.
    System.Diagnostics.Debug.WriteLine(k + " = " + qscoll[k]);
}
于 2012-10-19T11:57:06.830 回答
3

HttpUtility.ParseQueryString

使用 UTF8 编码将查询字符串解析为 NameValueCollection。

http://msdn.microsoft.com/en-us/library/ms150046.aspx

于 2012-10-19T11:57:28.207 回答
0

我知道这有点像僵尸帖子,但我想我会添加另一个答案,因为HttpUtility添加了另一个程序集引用 ( System.Web),这可能对某些人来说是不受欢迎的。

    using System.Net;
    using System.Text.RegularExpressions;

    static readonly Regex HttpQueryDelimiterRegex = new Regex(@"\?", RegexOptions.Compiled);
    static readonly Regex HttpQueryParameterDelimiterRegex = new Regex(@"&", RegexOptions.Compiled);
    static readonly Regex HttpQueryParameterRegex = new Regex(@"^(?<ParameterName>\S+)=(?<ParameterValue>\S*)$", RegexOptions.Compiled);

    static string GetPath(string pathAndQuery)
    {
        var components = HttpQueryDelimiterRegex.Split(pathAndQuery, 2);
        return components[0];
    }

    static Dictionary<string, string> GetQueryParameters(string pathAndQuery)
    {
        var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        var components = HttpQueryDelimiterRegex.Split(pathAndQuery, 2);

        if (components.Length > 1)
        {
            var queryParameters = HttpQueryParameterDelimiterRegex.Split(components[1]);

            foreach(var queryParameter in queryParameters)
            {
                var match = HttpQueryParameterRegex.Match(queryParameter);

                if (!match.Success) continue;

                var parameterName = WebUtility.HtmlDecode(match.Groups["ParameterName"].Value) ?? string.Empty;
                var parameterValue = WebUtility.HtmlDecode(match.Groups["ParameterValue"].Value) ?? string.Empty;

                parameters[parameterName] = parameterValue;
            }
        }

        return parameters;
    }

我希望他们会添加从 .NET 4.0WebUtility开始可用的相同方法。System.Net

于 2014-01-30T07:21:44.990 回答