日期:2014-05-18 浏览次数:20414 次
/// <summary> /// 返回解码后的字符串 /// </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; } 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; }