C# 获取url中的查询字符串参数

时间:2022-01-03 12:41:40
/// <summary>
/// 获取url中的查询字符串参数
/// </summary>
public static NameValueCollection ExtractQueryParams(string url)
{
int startIndex = url.IndexOf("?");
NameValueCollection values = new NameValueCollection(); if (startIndex <= )
return values; string[] nameValues = url.Substring(startIndex + ).Split('&'); foreach (string s in nameValues)
{
string[] pair = s.Split('='); string name = pair[];
string value = string.Empty; if (pair.Length > )
value = pair[]; values.Add(name, value);
} return values;
}
///   <summary>
/// 解码URL.
/// </summary>
/// <param name="encoding"> null为自动选择编码 </param>
/// <param name="str"></param>
/// <returns></returns>
public static string MyUrlDeCode( string str, Encoding encoding)
{
if (encoding == null )
{
Encoding utf8 = Encoding.UTF8;
// 首先用utf-8进行解码
string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
// 将已经解码的字符再次进行编码.
string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
if (str == encode)
encoding = Encoding.UTF8;
else
encoding = Encoding.GetEncoding( " gb2312 " );
}
return HttpUtility.UrlDecode(str, encoding);
}

using System.Security.Cryptography;
using System.Collections.Specialized;

NameValueCollection col = ExtractQueryParams("partnerId=12546&action=getProduct&timestamp=1560850762&nonce=8ObVcFPmverVgKth&sign=ea93f793f67e3a442fd8ad2bdf61e70e&data=FxsFyiX2s7M3zsnRzpkvGe6oOeLvmN1Q0u24cC1YX3PBU8fE9KA%2BOwU2RFD%2F4yhglONDiFC3te5Cqe0%2FLrfkZQcsUefPieWWo8K2GlOAA4OQBu3Y9YX8xkWTNPPcWjHLN%2BMd%2BOR%2B6fHL0AxQgKBNdTSKdOR9fo9WUZa1Snvh%2Bww%3D");
string searchKey = col["action"];
Response.Write(searchKey);