WebAPI接口对接:
提示:此片文章是总结接口对接经验其中包括模型的建立以及统一的调用
学习内容:
- 数据对象模型的建立
- 如何规范定义模型
- 统一的请求方法
- 系统中model的命名
- 请求接口时ASCII排序的处理
接口的数据传输对象包括Request对象和Response对象
每一个接口都单独建立一个文件夹
定义一个统一的父类(这是Request的统一父类)
GetApi方法是用于获取接口请求路径用的 (这里要注意Request是继承ResPonse的)
这里是Response的父类,父类中又接口的公用属性,每个接口返回都又这些参数。
接下来我们来看一个接口的返回和请求类
请求数据传输对象
返回数据对象
当然你有可以继承这个请求方法的接口去根据每一个接口的需求重写它
例如
其实这种写法用到的领域驱动设计
系统中model的命名规则
关于DO,DTO和VO在项目
DO:对应数据库表结构
VO:一般用于前端展示用
DTO:用于数据传递(接口入参和接口返回值都可以)
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;
}