asp.net中webservice請求發送原理和過程的初步分析[原]

來源:互聯網
上載者:User

需求:作為服務方,需要監控每個調用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。

 

測試代碼:

 

Code
//用戶端調用代碼
Write("Client端構建對象開始");
            ws.Service1 s = new WSWeb.ws.Service1();
            Write("Client端構建對象完畢");

            Write("Client端開始調用HelloWorld");
            s.HelloWorld();
            Write("Client端調用HelloWorld完畢");

            Write("Client端開始調用MyTestMethod");
            s.MyTestMethod("sssssssssssssttttt");
            Write("Client端調用MyTestMethod完畢");

 

Code
 Write("進入伺服器端基類構造方法");

            System.IO.FileInfo fi = new System.IO.FileInfo(PATH);
            if (!fi.Exists)
                fi.Create();

            HttpRequest req = HttpContext.Current.Request;
            System.IO.Stream stream = req.InputStream;
            stream.Position = 0;
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);

            StringBuilder sbRequest = new StringBuilder();
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                sbRequest.Append(line + "\n");
            }

            Write(sbRequest.ToString());

            Write("離開 伺服器端基類構造方法");

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.