C#調用WebService時和JS調用時有很多相似的地方,讓我們來一步一步實現:
第一步:建立一個WebService
這一步和JS調用WebService相同,在此不多說了。詳細可訪問如下地址:
地址:<http://www.cnblogs.com/puresoul/archive/2010/08/19/1803567.html>
第二步:建立一個頁面,實現C#調用Web服務
在頁面上添加一個按鈕,後台代碼如下:
代碼
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7
8 using MSXML2;
9
10 public partial class Default4 : System.Web.UI.Page
11 {
12 protected void Page_Load(object sender, EventArgs e)
13 {
14
15 }
16 protected void Button1_Click(object sender, EventArgs e)
17 {
18 //Web服務的地址
19 string URL = "http://localhost/YBWS/WebService.asmx";
20
21 //拼接資料
22 string data;
23 data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
24 data = data + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">";
25 data = data + "<soap12:Body>";
26 data = data + "<HelloWorld xmlns=\"http://tempuri.org/\" />";
27 data = data + "</soap12:Body>";
28 data = data + "</soap12:Envelope>";
29
30 //建立非同步對象(XMLHTTP對象在MSXML2下)
31 XMLHTTP xmlhttp = new XMLHTTP();
32 xmlhttp.open("POST", URL, false, null, null);
33 xmlhttp.setRequestHeader("Content-Type", "application/soap+xml");
34 xmlhttp.send(data);
35 Response.Write(System.Text.Encoding.UTF8.GetString((byte[])xmlhttp.responseBody));
36 Response.End();
37 }
38 }
39
當點擊按鈕時,效果如: