Asp.Netの[文字列Url]パラメータ処理

2734 ワード

まず、msdn Uriクラスを見てみましょう.Uriクラスはこの文章とは関係ありません.ただ、検索を便利にするためです.
        /// <summary>
        ///     url     ?    , Dictionary<key, value>    
        /// </summary>
        /// <param name="url">url</param>
        /// <returns>Dictionary<key, value>    </returns>
        public static Dictionary<string, string> GetParams(string url)
        {
            int intPos = url.IndexOf("?");
            if (url == null || url.Length < 1 || intPos < 1)
            {
                return null;
            }
            else
            {
                Dictionary<string, string> dt = new Dictionary<string, string>();
                string strRight = url.Substring(intPos + 1);
                string[] arrPram = StringSplit(strRight, "&");
                for (int i = 0; i < arrPram.Length; i++)
                {
                    string[] arrPramName = StringSplit(arrPram[i], "=");
                    dt.Add(arrPramName[0].ToLower(), arrPramName[1].ToLower());
                }
                return dt;
            }
        }


        /// <summary>
        ///     key:value      url     key  ,     ,       key=value
        /// </summary>
        /// <param name="url">  url</param>
        /// <param name="key">    key  </param>
        /// <param name="value">  Value</param>
        /// <returns>     url</returns>
        public static string ReplaceUrlParam(string url, string key, string value)
        {
            string new_returnurl = "";
            Dictionary<string, string> d = Safe.GetParams(url.ToLower());
            d = d ?? new Dictionary<string, string>();
            if (d.ContainsKey(key))
            {
                d.Remove(key);
                d.Add(key, value);
            }
            else
            {
                d.Add(key, value);
            }
            if (d != null && d.Count > 0)
            {
                int i = 0;
                foreach (KeyValuePair<string, string> kv in d)
                {
                    if (i == 0)
                    {
                        new_returnurl += "?" + kv.Key + "=" + kv.Value;
                    }
                    else
                    {
                        new_returnurl += "&" + kv.Key + "=" + kv.Value;
                    }
                    i++;
                }
            }
            new_returnurl = url.Split('?')[0] + new_returnurl;
            return new_returnurl;
        }