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為何不是最后一個參數我明天再看看。

這里就是將子類強制轉化為父類的對象傳過去目的也就是為了調用這個參數信息吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM