2011年9月14日 星期三

ASP 呼叫 .NET Web Service

為了讓 ASP 呼叫 .NET 的 Web Service
上網查了好久的資料
查到有 2 種方式可以達成
   1. 使用 XMLHTTP 呼叫
   2. 使用 SOAP 呼叫
最後決定用 XMLHTTP 的方式呼叫
因為 SOAP 要另外在 ASP 端安裝 SOAP Toolkit

在這邊記錄一下 XMLHTTP 呼叫 Web Service 的方法

<%
   Set objHttp = Server.CreateObject("MSXML2.XMLHTTP")
   Set xmlDOC = Server.CreateObject("MSXML.DOMDocument")

   ' Web Service 網址 (最後面加要呼叫的Function Name)
   ws_url = "http://localhost/TestWebService/Service.asmx/Add"

   ' Web Service 要傳入的參數
   ws_params = "Param1=" & 1 & "&Param2=" & 3

   ' Web Service 的 web.config 要在 <system.web> </system.web> 中設定
   ' <webservices>
   '    <protocols>
   '        <add name="HttpPost"/>
   '        <add name="HttpGet"/>
   '    </protocols>
   ' </webServices>
   objHttp.Open "POST", ws_url, False
   objHttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
   objHttp.Send(ws_params)
   xmlDOC.load(objHttp.responseXML)

   if objHttp.Status = 200 then
      xmlStr = xmlDOC.xml
      Response.Write Replace(Replace(xmlStr,"<","&lt;"),">","&gt;")
   else
      Response.Write "Error : " & objHttp.StatusText & "(" & objHttp.Status & ")"
   end if
%>