C# 解析URL 获取参数 【string转Dic】

主要用于解析Url后缀参数

Eg: UploadType=0&Infocode=1&AttachName=2&Seq=3&Cid=4

 public static Dictionary<string, string> ParseQueryString(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return new Dictionary<string, string>();
            }
            var uri = new Uri(url);
            if (string.IsNullOrWhiteSpace(uri.PathAndQuery))
            {
                return new Dictionary<string, string>();
            }

            var paramStr = uri.PathAndQuery;

            //1.去除第一个前导?字符
            if (uri.PathAndQuery.StartsWith('?'))
                paramStr = uri.PathAndQuery.Substring(1);
          
            var dic = paramStr
                    .Split('&', StringSplitOptions.RemoveEmptyEntries)//2.通过&划分各个参数
                    .Select(param => param.Split( '=', 2, StringSplitOptions.RemoveEmptyEntries))//3.通过=划分参数key和value,且保证只分割第一个=字符
                    .GroupBy(part => part[0], part => part.Length > 1 ? part[1] : string.Empty)//4.通过相同的参数key进行分组
                    .ToDictionary(group => group.Key, group => string.Join(",", group));//5.将相同key的value以,拼接

            return dic;
        }
posted @ 2022-03-31 15:56  C余L小R鱼  阅读(728)  评论(0编辑  收藏  举报