利用委托与Lambada创建和调用webapi接口(含源码)前言前不久有对此做过一次总结。但是不够详细,今天整理重发一次。 现在项目中用的是webapi,其中有以下问题:1.接口随着开发的增多逐渐增加相当庞大。 2.接口调用时不好管理。 以上是主要问题,对此就衍生了一个想法: 如果每一个接口都一个配置文件来管理,每个配置文件能清晰表示处理接口文件,地址,参数,返回值,那么通过这个配置文件,就能很好的管理起来我们所有的webapi接口不是吗? 有了这个思路之后就有了以下的实现: 1.具体实现:
View Code
1.1.Build_Apis()方法是系统根据,webapi接口描述,创建的对应的接口服务配置文件操作。 配置如下: 生成接口文件如下: 接口的实现 接下来只需你把xml文件引用到你要调用的站点下即可。 public string Load_Apis()
{
var files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "apis_*.xml", System.IO.SearchOption.AllDirectories);
apis.Clear();
foreach (var path in files)
{
var jss = System.IO.File.ReadAllText(path);
var _apis = Deserialize<List<WebApiNode>>(jss);
if (_apis == null || _apis.Count == 0) continue;
foreach (var api in _apis)
{
if (apis.Exists(a => a.Service == api.Service)) continue;
apis.Add(api);
}
}
return string.Format("service:{0}, action:{1}", apis.Count, apis.Sum(a => a.Methods.Count));
}
1.2:Load_Apis()在程序启动时加载webapi服务配置文件的操作,在这不再累述。
View Code
1.3:其中 result<tresp> _invoke通过lambda对传递过来的委托,进行相应的反射操作。 其中委托定义如下: public delegate IHttpActionResult apiaction();
public delegate IHttpActionResult apiaction_l(long args);
public delegate IHttpActionResult apiaction_ll(long args1, long args2);
public delegate IHttpActionResult apiaction_li(long args1, int arg2);
public delegate IHttpActionResult apiaction_ls(long args1, string args2);
public delegate IHttpActionResult apiaction_i(int args1);
public delegate IHttpActionResult apiaction_ii(int args1, int args2);
public delegate IHttpActionResult apiaction_is(int args1, string args2);
public delegate IHttpActionResult apiaction_il(int args1, long args2);
public delegate IHttpActionResult apiaction_si(string args1, int args2);
public delegate IHttpActionResult apiaction_ss(string args1, string args2);
public delegate IHttpActionResult apiaction_sl(string args1, long args2);
public delegate IHttpActionResult apiaction_sss(string args1, string args2, string args3);
public delegate IHttpActionResult apiaction_o<treq>(treq data) where treq : class,new();
注:目前delegate只支持三个参数以内的接口(且参数类型目前仅支持int,long,string),如果参数不符合条件可传递对象。 以上为具体实现至于有不了解的可以在文章顶部下载代码也可以,点击公共中qq与我联系。 2.下面我来写一下它的使用:2.1.初始化:在global中添加如下代码: 2.2.在mvc中调用:源码地址:https://github.com/kmonkey9006/QuickWebApi
|
|