通过POST解析(Parse through POST)

2019-09-24 07:42发布

我使用流阅读器来阅读context.Request.InputStream至年底,并用绳子看起来像结束

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

什么是最efficent /“干净”的方式来解析在C#控制台?

Answer 1:

您可以使用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]);
}


Answer 2:

HttpUtility.ParseQueryString

解析查询字符串到使用UTF8编码一个NameValueCollection中。

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



Answer 3:

我知道这是一个有点僵尸后,但我想我会添加其他的答案,因为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;
    }

我希望他们能加入到相同的方法WebUtility它可在System.Net作为.NET 4.0。



文章来源: Parse through POST