C#反射(开发接口功能,类似WebService返回json)

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 这个方法

地址如下http://localhost:8010/study/api/service.ashx?api_key=d3aa11dc88b5ca0b55aed3596ed75b25&method=System.System.IsReachMobileMaxOnline&call_id=635593553999088080&memberid=&customerid=02730f58-d041-4d63-a523-942ea0579cd7&sig=239A3BF89ABF18DB30F0D76DBA7BFB8F

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为何不是最后一个参数我明天再看看。

这里就是将子类强制转化为父类的对象传过去目的也就是为了调用这个参数信息吧。

 

转载于:https://www.cnblogs.com/liyunzhi/articles/4288518.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值