WebService的開發、部署、調用


本文參考其它文章和自己解決中間問題的經歷記錄,以C#開發WebService為例子,歡迎探討:

一、C#開發WebService

  1. 在visual studio中新建ASP.NET Web服務應用程序,取名MyWebService。
  2. 刪除自動生成的代碼,輸入以下代碼段,包括多個方法:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace WebServicetest
{
    /// <summary>
    /// Service1 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://192.168.1.201")]    //為自己以后webservice發布虛擬目錄所在的域名
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的注釋。
    [System.Web.Script.Services.ScriptService]   //啟動對腳本的支持
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod(Description = "默認的方法")]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod(Description = "求和的方法")]
        public double addition(double i, double j)
        {
            return i + j;
        }
        [WebMethod(Description = "求差的方法")]
        public double subtract(double i, double j)
        {
            return i - j;
        }
        [WebMethod(Description = "求積的方法")]
        public double multiplication(double i, double j)
        {
            return i * j;
        }
        [WebMethod(Description = "參數返回中文方法")]
        public string myhello(string name, string department)
        {
            return "您的姓名:" + name + "<br>" + "您的單位:" + department + "<br>";
        }

    }
}

 

初步生成后,可以CTRL+F5啟動自帶的調試器測試WebService,查看定義的調用方法,如下圖所示:

點擊具體的方法,可以測試。

調用測試結果如下:

 

二、WebService部署

  1. 調試通過后發布WebService。
  1. 將發布后的文件目錄拷貝的Web服務器(安裝有IIS的機器),創建虛擬目錄,和發布網站一樣,指向該目錄。如下圖:

遠程地址:http://192.168.1.201/myservice/service1.asmx(該服務器的IP地址為:192.168.1.201)為了測試可行性,在客戶端輸入這個網址進行測試,看能否訪問調用。如下圖:

我們會發現,從遠程客戶端訪問服務器上的WebService能夠顯示,但點擊調用相關的方法時顯示“只能用於來自本地計算機的請求”,這時提醒我們還需要在服務器進行相關的配置才能讓其他機器正常訪問該WebService。具體配置方法如下:

修改webconfig文件,在system.web節點下面加入下面代碼?:

<webServices > 
<protocols > 
<add name="HttpSoap"/> 
<add name="HttpPost"/> 
<add name="HttpGet"/> 
<add name="Documentation"/> 
</protocols> 
</webServices>

即可實現遠程訪問webservice。最終效果如圖:

三、WebService的調用

 

1.在asp.net中調用(轉自http://www.cnblogs.com/xuetuyuan/archive/2011/02/22/1961322.html)

(1)新建ASP.NET Web應用程序,在Default.aspx頁面中添加控件如下:

(2)添加Web引用,Web引用名:WebReference。如下圖:

 

(3)添加相關調用代碼如下:

public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            WebReference.WebServiceDemo s = new WebReference.WebServiceDemo();

            //調用WebService的HelloWorld方法,返回"HelloWorld",並輸出.

            Response.Write(s.HelloWorld());

        }

        protected void btnConvert_Click(object sender, EventArgs e)

        {

            WebReference.WebServiceDemo s = new WebReference.WebServiceDemo();

            //調用WebService的ConvertTemperature方法,實現溫度轉換.

            labResult.Text = "轉換后的溫度是:" + s.ConvertTemperature(double.Parse(txtResult.Text));

        }

}

 

(4)測試結果如下:

 

2.js調用webservice+xmlhttp的實現部分(轉自http://www.zahui.com/html/4/37953.htm)

<html>
 <title>Call webservice with javascript and xmlhttp.</title>
<body>
 <mce:script language="javascript"><!--
 

 //test function with get method.
 function RequestByGet(data){ 
  var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
  //Webservice location.
  var URL="http://localhost:1323/WebSite6/Service.asmx/SayHelloTo?Name=Zach";
  xmlhttp.Open("GET",URL, false); 
  xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8"); 
  xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo"); 
  xmlhttp.Send(data); 
  var result = xmlhttp.status; 
  //OK
  if(result==200) { 
   document.write(xmlhttp.responseText); 
  } 
  xmlhttp = null; 
 }

 //test function with post method
 function RequestByPost(value)
 {
  var data;
  data = '<?xml version="1.0" encoding="utf-8"?>'; 
  data = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
  data = data + '<soap:Body>'; 
  data = data + '<SayHelloTo xmlns="http://tempuri.org/">'
  data = data + '<Name>'+value+'</Name>'; 
  data = data + '</SayHelloTo>'; 
  data = data + '</soap:Body>'; 
  data = data + '</soap:Envelope>';

  var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
  var URL="http://localhost:1323/WebSite6/Service.asmx";
  xmlhttp.Open("POST",URL, false); 
  xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=gb2312"); 
  xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo"); 
  xmlhttp.Send(data); 
  document.write( xmlhttp.responseText); 
 }

 
// --></mce:script>

 <input type="button" value="CallWebserviceByGet" onClick="RequestByGet(null)">
 <input type="button" value="CallWebserviceByPost" onClick="RequestByPost('Zach')">
</body>
</html>

其中webservice的地址可以換成已經發布好的遠程服務器地址即可,該代碼未經測試,正確性不予保證。

 

3.通過js簡單調用webservice(經過測試,能夠運行,但IE9不兼容)

(1)客戶端代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WebServiceTest</title>
<script language="javascript">
var intCallID;
function init()
{


//第一個參數是webservice的url,后面是名稱

 hello.useService("http://192.168.1.201/myservice/service1.asmx?WSDL","MyName");  
}

function calltest()
{
 //如果該webservice有參數的話,在括號后加逗號分隔。
 intCallID=hello.MyName.callService("myhello",document.getElementsByName("name")[0].value,document.getElementsByName("department")[0].value); //no param
 }

function callback_result()
{
 if ((event.result.error)&&(intCallID==event.result.id))
    {
     var xfaultcode = event.result.errorDetail.code;
     var xfaultstring = event.result.errorDetail.string;
      var xfaultsoap = event.result.errorDetail.raw;

       // Add code to output error information here
       alert(xfaultstring);
    }
    else
    {
       hello.innerHTML+= "測試調用結果為:<br>"+ event.result.value;
    }
 
}
</script>
</head>

<body onload="init();">
<p>&nbsp;</p>
<label>姓名:
  <input type="text" name="name" id="name" />
  <br />
  單位:
  <input type="text" name="department" id="department" />
  <br />
</label>
<div id="hello"  style="behavior:url(webservice.htc)" onresult="callback_result();" ></div>
<input name="button" type="button" onClick="calltest();" value="調用測試" />
</body>
</html>

調用測試界面如圖:

填入參數,點擊按鈕,頁面DIV刷新變化為:

 

通過javascript和webservice.htc附加到HTML元素(例如DIV)調用法有以下幾個注意問題:

a.由於js不能跨域調用,而導致調用頁面和webservice所在網站不在同一服務器會導致問題,解決方法查找相關資料如下:

出於安全考慮禁止跨域調用其他頁面的對象,因此也導致了js使用跨域的web service成為問題。解決方法: 
1.設置document.domain 
前提條件:兩個頁面同屬於一個基礎域(例如都是xxx.com,或是xxx.com.cn);同一協議(例如都是http);同一端口(例如都是80)。 
方法:設置兩個頁面的document.domain都設置為自己所在的基礎域名。 
例子:aaa.xxx.com里面的一個頁面需要調用bbb.xxx.com里的一個對象,則將兩個頁面的document.domain都設置為xxx.com,就可以了。 

2.在服務器端設置代理 
跨域的請求同樣發送到本地服務器端,由服務器端的代理來請求相應的數據,然后發送給瀏覽器端。這樣實際上瀏覽器端的所有請求都是發到相同的域,在服務器端代理的幫助下,實現了跨域的能力。 
3.使用 標簽 
當同時具有兩個域的開發權限時就可以使用該方法了,原理是JS文件注入,在本域內的a內生成一個JS標簽,SRC指向請求的另外一個域的某個頁面b,b返回數據即可,可以直接返回JS的代碼。

b.利用JS調用webservice需要用到微軟的webservice.htc文件,可以在微軟官方網站下載到,放到和調用頁面同路徑即可。例如:<div id="hello"  style="behavior:url(webservice.htc)" onresult="callback_result();" ></div>

 

 

其它諸如返回多值、例如數組等,兼容性問題(經測試IE9不兼容js調用方法),更高級應用方法還有待進一步應用,此文章僅興趣測試而寫,不周之處,口下留情!當然也歡迎網友多多指導,告以其中謬誤和原理!


免責聲明!

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



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