我使用流阅读器来阅读context.Request.InputStream
至年底,并用绳子看起来像结束
"Gamestart=true&GamePlayer=8&CurrentDay=Monday&..."
什么是最efficent /“干净”的方式来解析在C#控制台?
我使用流阅读器来阅读context.Request.InputStream
至年底,并用绳子看起来像结束
"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。