c# 對Url 解碼編碼


   /// <summary>
        /// 對Url進行編碼
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="isUpper">編碼字符是否轉成大寫,范例,"http://"轉成"http%3A%2F%2F"</param>
        public static string UrlEncode(string url, bool isUpper = false)
        {
            return UrlEncode(url, Encoding.UTF8, isUpper);
        }

        /// <summary>
        /// 對Url進行編碼
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="encoding">字符編碼</param>
        /// <param name="isUpper">編碼字符是否轉成大寫,范例,"http://"轉成"http%3A%2F%2F"</param>
        public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
        {
            var result = HttpUtility.UrlEncode(url, encoding);
            if (!isUpper)
                return result;
            return GetUpperEncode(result);
        }

        /// <summary>
        /// 獲取大寫編碼字符串
        /// </summary>
        private static string GetUpperEncode(string encode)
        {
            var result = new StringBuilder();
            int index = int.MinValue;
            for (int i = 0; i < encode.Length; i++)
            {
                string character = encode[i].ToString();
                if (character == "%")
                    index = i;
                if (i - index == 1 || i - index == 2)
                    character = character.ToUpper();
                result.Append(character);
            }
            return result.ToString();
        }
  /// <summary>
        /// 對Url進行解碼,對於javascript的encodeURIComponent函數編碼參數,應使用utf-8字符編碼來解碼
        /// </summary>
        /// <param name="url">url</param>
        public static string UrlDecode(string url)
        {
            return HttpUtility.UrlDecode(url);
        }

        /// <summary>
        /// 對Url進行解碼,對於javascript的encodeURIComponent函數編碼參數,應使用utf-8字符編碼來解碼
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="encoding">字符編碼,對於javascript的encodeURIComponent函數編碼參數,應使用utf-8字符編碼來解碼</param>
        public static string UrlDecode(string url, Encoding encoding)
        {
            return HttpUtility.UrlDecode(url, encoding);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM