通过解析POST

通过解析POST

问题描述:

我使用流阅读器来阅读context.Request.InputStream的结束,以及看起来像通过解析POST

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

字符串结束了,会是什么最efficent /“干净”的方式来解析在C#控制台?

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

HttpUtility.ParseQueryString

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

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

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