现在项目中用的是webapi,其中有以下问题:
1.接口随着开发的增多逐渐增加相当庞大。
2.接口调用时不好管理。
以上是主要问题,对此就衍生了一个想法:
如果每一个接口都一个配置文件来管理,每个配置文件能清晰表示处理接口文件,地址,参数,返回值,那么通过这个配置文件,就能很好的管理起来我们所有的webapi接口不是吗?
有了这个思路之后就有了以下的实现:
1.具体实现:
public void Build_Apis() { foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetCustomAttributes(typeof(QuickWebApiDllAttribute), true).Length > 0)) { var vatt = ass.GetCustomAttribute<AssemblyFileVersionAttribute>(); var tatt = ass.GetCustomAttribute<AssemblyTitleAttribute>(); var datt = ass.GetCustomAttribute<QuickWebApiDllAttribute>(); apis.Clear(); var input_types = new List<Type>(); foreach (var type in ass.GetTypes()) { var attr = type.GetCustomAttribute<QuickWebApiAttribute>(); if (attr != null) { WebApiNode api = new WebApiNode(datt.Domain) { Name = attr.name, Service = attr.service, Route = attr.route, Comment = attr.comment, Version = vatt.Version, Title = tatt.Title }; foreach (var mi in type.GetMethods()) { var att = mi.GetCustomAttribute<QuickWebApiAttribute>(); if (att != null) { var act = new WebApiMethod() { Action = mi.Name, Code = att.service, Method = att.methodtype, Name = string.IsNullOrWhiteSpace(att.name) ? mi.Name : att.name, Comment = att.comment, OutputType = att.resultype }; foreach (var arg in mi.GetParameters()) { var mdatt = arg.ParameterType.GetCustomAttribute<DescriptionAttribute>(); act.Params.Add(new WebApiMethodParam() { Name = arg.Name, TypeName = arg.ParameterType.Name, DefaultValue = string.IsNullOrWhiteSpace(arg.DefaultValue.ToString()) ? "无默认值" : arg.DefaultValue.ToString(), Desc = mdatt == null ? "" : mdatt.Description }); if (arg.ParameterType.IsClass && arg.ParameterType != typeof(string)) { if (!input_types.Exists(t => t.Name == arg.ParameterType.Name)) input_types.Add(arg.ParameterType); } } if (!api.Methods.Exists(a => a.Action == act.Action)) api.Methods.Add(act); if (att.resultype != null && att.resultype.IsClass && att.resultype != typeof(string)) { if (!input_types.Exists(t => t.Name == att.resultype.Name)) input_types.Add(att.resultype); } } } if (!apis.Exists(a => a.Service == api.Service)) apis.Add(api); } } Build_Apids_Config(apis, datt.Name); Build_Apids_Doc(apis, datt.Name, input_types); } }