C#请求接口时需要进行ASCII排序

C#请求接口时需要进行ASCII排序

这种需求一般都是在对接接口时签名会需要这样处理
这种情况我们一般都是通过数据字典进行数据处理。

//这里就是传入对象进行ASCII排序然后加密。作为签名
  public static string GetSigin(object Params)
        {
    
    
            Dictionary<string, string> paramsMap = GetProperties(Params);
            //这里是因为我的请求对象里包含了sgin这个属性,而签名不能出现这个属性所有需要进行删除。
            paramsMap.Remove("sign");
            var vDic = (from objDic in paramsMap orderby objDic.Key ascending select objDic);
            StringBuilder str = new StringBuilder();
            foreach (KeyValuePair<string, string> kv in vDic)
            {
    
    
                string pkey = kv.Key;
                string pvalue = kv.Value;
                str.Append(pkey + "=" + pvalue + "&");
            }
            String result = str.ToString().Substring(0, str.ToString().Length - 1);
            //RSAWithSha256加密方法
            return RSAWithSha256.SignPrivate(result);
        }


//这里是通过反射获取对象里面的属性
 public static Dictionary<string, string> GetProperties<T>(T t)
        {
    
    
            Dictionary<string, string> ListStr = new Dictionary<string, string>();
            if (t == null)
            {
    
    
                return ListStr;
            }
            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (properties.Length <= 0)
            {
    
    
                return ListStr;
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
    
    
                string name = item.Name; //名称
                object value = item.GetValue(t, null);  //值

                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
    
    
                    ListStr.Add(name, (value ?? "").ToString());
                }
                else
                {
    
    
                    ListStr.Add(name, JsonConvert.SerializeObject(value));
                }
            }
            return ListStr;
        }

猜你喜欢

转载自blog.csdn.net/qq_42455262/article/details/128532372
今日推荐