/// /// 编码 /// /// /// /// public static string ToEncode(this string uri, string charset = "utf-8") { string URL_ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; if (string.IsNullOrEmpty(uri)) return string.Empty; const string escapeFlag = "%"; var encodedUri = new StringBuilder(uri.Length * 2); var bytes = Encoding.GetEncoding(charset).GetBytes(uri); foreach (var b in bytes) { char ch = (char)b; if (URL_ALLOWED_CHARS.IndexOf(ch) != -1) encodedUri.Append(ch); else { encodedUri.Append(escapeFlag).Append(string.Format(CultureInfo.InstalledUICulture, "{0:X2}", (int)b)); } } return encodedUri.ToString(); } /// /// 解码 /// /// /// public static string ToDecode(this string uriToDecode) { if (!string.IsNullOrEmpty(uriToDecode)) { uriToDecode = uriToDecode.Replace("+", " "); return Uri.UnescapeDataString(uriToDecode); } return string.Empty; }