C#分析URL参数获取参数和值得对应列表

时间:2022-05-23 09:21:38

原文: C#分析URL参数获取参数和值得对应列表

  /// <summary>
/// 分析url链接,返回参数集合
/// </summary>
/// <param name="url">url链接</param>
/// <param name="baseUrl"></param>
/// <returns></returns>
public static System.Collections.Specialized.NameValueCollection ParseUrl(string url, out string baseUrl)
{
baseUrl = "";
if (string.IsNullOrEmpty(url))
return null;
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection(); try
{
int questionMarkIndex = url.IndexOf('?'); if (questionMarkIndex == -)
baseUrl = url;
else
baseUrl = url.Substring(, questionMarkIndex);
if (questionMarkIndex == url.Length - )
return null;
string ps = url.Substring(questionMarkIndex + ); // 开始分析参数对
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", System.Text.RegularExpressions.RegexOptions.Compiled);
System.Text.RegularExpressions.MatchCollection mc = re.Matches(ps); foreach (System.Text.RegularExpressions.Match m in mc)
{
nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
} }
catch { }
return nvc;
}