Пример #1
0
        public static string ToUrlFormat(this System.Collections.Specialized.NameValueCollection Collection, IDictionary <string, string> FormatList, UrlEncodeType encodeType, Encoding encoding, bool KeepEmpty, out Dictionary <string, string> OverDict)
        {
            if (FormatList == null)
            {
                FormatList = new Dictionary <string, string>();
            }
            //首先获取全部Key
            IEnumerable <string> FormatKey = FormatList.Keys.Tolower();

            OverDict = new Dictionary <string, string>();
            //把输入字典传进过滤字典里面,重复的不叠加
            foreach (var ckey in Collection.AllKeys.Reverse())
            {
                if (ckey == null)
                {
                    continue;
                }
                if (!FormatKey.Contains(ckey.ToLower()))
                {
                    FormatList.Add(ckey, Collection[ckey]);
                }
                else
                {
                    OverDict.Add(ckey, Collection[ckey]);
                }
            }

            //倒转序列
            var temp = FormatList.Reverse();


            StringBuilder sb = new StringBuilder();

            sb.Append("?");
            if (temp.Count() == 0)
            {
                return("");
            }
            foreach (var item in temp)
            {
                if (item.Value == null)
                {
                    if (!KeepEmpty)
                    {
                        sb.AppendFormat("{0}=&", item.Key);
                    }
                    continue;
                }
                if (item.Value.IndexOf("{0}") >= 0)
                {
                    sb.AppendFormat("{0}={1}&", item.Key, item.Value.ToString()); continue;
                }
                switch (encodeType)
                {
                case UrlEncodeType.HtmlEncode:
                    sb.AppendFormat("{0}={1}&", item.Key, System.Web.HttpUtility.HtmlEncode(item.Value.ToString()));
                    break;

                case UrlEncodeType.UrlEncode:
                    if (encoding != null)
                    {
                        sb.AppendFormat("{0}={1}&", item.Key, System.Web.HttpUtility.UrlEncode(item.Value.ToString(), encoding));
                    }
                    else
                    {
                        sb.AppendFormat("{0}={1}&", item.Key, System.Web.HttpUtility.UrlEncode(item.Value.ToString()));
                    }
                    break;

                case UrlEncodeType.NoEncode:
                    sb.AppendFormat("{0}={1}&", item.Key, item.Value.ToString());
                    break;
                }
            }
            return(sb.ToString());
        }