需求:作為服務方,需要監控每個調用webservice的用戶端。需要監控的資訊大致如下:用戶端的ip,用戶端調用了哪個類的哪個方法。
於是自己花了點時間對asp.net的webservice機製作了一下探索。
解決方案:
在介面項目中編寫一個所有webservice介面的基類,在此基類的構造方法中,通過分析HttpContext.Current.Request得到想要的資訊。
1.ip可以通過HttpContext.Current.Request.UserHostAddress得到
2.調用發哪個方法以及參數等都可以通過分析HttpContext.Current.Request.InputStream得到
這是我用下面的代碼輸出的InputStream的內容:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<MyTestMethod xmlns="http://tempuri.org/">
<msg>abcd</msg>
</MyTestMethod>
</soap:Body>
</soap:Envelope>
看到了吧?調用的方法是MyTestMethod,參數是msg,值是abcd
以下是測試的過程:
先把結論給出:
asp.net的程式在添加對webservice的引用時,用戶端會組建代理程式proxy類。
用戶端的調用代碼一般類似這樣:
ws.Service1 s = new WSWeb.ws.Service1();
s.HelloWorld();
s.MyTestMethod("sssssssssssssttttt");
1.在ws.Service1 s = new WSWeb.ws.Service1();運行這行時,並不會調用伺服器端的構造方法,而是調用本地產生的proxy類的構造方法。
2.只有在運行這行時:s.HelloWorld();才會將方法及參數形成soap,綁定到http,發送到伺服器端。此時,先調用伺服器端的構造方法,然後調用伺服器端的HelloWorld
運行第3行s.MyTestMethod("sssssssssssssttttt");時也是這樣,會先調一下伺服器端的構造方法,再調用伺服器端的MyTestMethod。