自己做个网站,发现百度的蜘蛛和Google的蜘蛛对Url的编码解码方式不一致,给我造成了很大的困惑啊,
做了一个函数,统一由此解码,世界清静了
顺便宣传一下网站地址 接龙大全
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(UrlDecode("xxx"));
}
/// <summary>
/// Url通用解码
/// 先尝试utf-8,再尝试gb2312
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string UrlDecode(string key)
{
string input = GetUrlParam(key).ToLower();
if (input.Length == 0)
return string.Empty;
//首先用utf-8进行解码
string result = HttpUtility.UrlDecode(input, Encoding.UTF8);
// 将已经解码的字符再次进行编码.
string encode = HttpUtility.UrlEncode(result, Encoding.UTF8).ToLower();
//与原来编码进行对比,如果不一致说明解码未正确,用gb2312进行解码
if (input != encode)
result = HttpUtility.UrlDecode(input, Encoding.GetEncoding("gb2312"));
return result;
}
/// <summary>
/// 获取Url的参数,不编码,只获取明码
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private static string GetUrlParam(string key)
{
if (System.Web.HttpContext.Current != null)
{
string query = HttpContext.Current.Request.Url.Query;
if (query != null && query.Length > 0)
{
int index = 0;
index = query.IndexOf(key + "=");
if (index >= 0)
{
query = query.Substring(key.Length + 1 + index);
index = query.IndexOf('&');
if (index >= 0)
query = query.Substring(0, index);
return query;
}
}
}
return string.Empty;
}