Webservice一直没深入研究过,对于c#开发人员一般进公司这东西都封装好了,所以也没什么研究机会。这次为公司做的移动端接口功能也差不多接近尾声(大多数都是业务逻辑方面)。
反射这个概念老早就有了,但是没深入过,回到接口上来。
将路径写入web.config的httpHandlers让特定程序处理
<add verb="*" path="service.ashx" type="Expo.Training.Services.RestService, Expo.Training.Services"/>
type逗号前是对应cs文件,后面是命名空间dll
RestService继承IHttpHandler

目录如下
我想执行的方法
System.System.IsReachMobileMaxOnline 这个方法
RestService重写public void ProcessRequest(HttpContext context)
然后获取参数列表进行对比,参数不对返回错误信息
然后获取
string classname = method.Substring(0, method.LastIndexOf('.'));//文件地址System.System string methodname = method.Substring(method.LastIndexOf('.') + 1);//方法IsReachMobileMaxOnline
好了接下来就是最关键的怎么进入该方法的
Type.GetType(string.Format("Expo.Training.Services.API.MobileApp.{0}, Expo.Training.Services", classname), false, true); action = (ActionBase)Activator.CreateInstance(type); action.ApiKey = apiKey; action.Params = parameters; action.Domain = context.Request.Url.Scheme+"://"+context.Request.Url.Authority; action.Secret = secretKey; action.Uid = memberid; action.Cid = customerid; action.Format = FormatType.JSON; action.Signature = sig; action.CallId = callid; action.LastCallId = lastcallid; if (format.Trim().ToLower() == "xml") { context.Response.ContentType = "text/xml"; action.Format = FormatType.XML; } content = type.InvokeMember(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase, null, action, new object[] { }).ToString();
1、Type.GetType,获取到对应名称Type类型
{Expo.Training.Services.API.MobileApp.System.System}
2、action = (ActionBase)Activator.CreateInstance(type);子类强制转化为父类
Activator.CreateInstance使用指定类型的默认构造函数来创建该类型的实例。
System.System.cs 继承了ActionBase
3、为ActionBase添加参数信息
4、type.InvokeMember执行方法
BindingFlags设置筛选设置
type已经是对应类型了 然后传参调用。
关于这个action为何不是最后一个参数我明天再看看。
这里就是将子类强制转化为父类的对象传过去目的也就是为了调用这个参数信息吧。
