使用ASP.NET构造一个简单的XML Web服务是相对容易的,然而,XML Web服务的真正的强大的功能只有等你研究了基础结构以后才能领悟。XML Web服务是建立在.NET框架和公共语言运行时间基础上的。一个XML Web服务可以利用这些技术。例如,ASP.NET支持的性能、状态管理和验证全都可被用来构造XML Web服务。
XML Web服务的基础结构是构建来符合象SOAP、XML和WSDL这样的行业标准,并且它允许其他的平台的客户端与XML Web服务互操作。只要一个客户端可以发送符合标准的SOAP消息、依据格式化的服务描述,那么这个客户端可以调用一个使用ASP.NET创建的XML Web服务(不管客户端存在于何种平台)。
当你使用ASP.NET构造一个XML Web服务时,它自动支持客户端使用SOAP、HTTP-GET和HTTP-POST协议通讯。即使HTTP-GET和HTTP-POST支持使用URL编码的变量名/变量值对来传送消息,支持这两个协议的数据类型也没有支持SOAP协议的数据类型丰富。在SOAP中,使用XML把数据传送到XML Web服务或从XML Web服务取回消息,你可以使用支持丰富的数据类型集的XSD模式定义复杂的数据类型。使用ASP.NET构造一个XML Web服务的开发者不必明确地定义复杂的数据类型。他们可以只构造一个管理类。ASP.NET处理定义到一个XSD模式的映射类和到XML数据的映射对象实例,以便通过网络传输。
重要的是要注意XML Web服务并不能取代DCOM,我们应该说XML Web服务是跨越使用行业标准的平台通信的一种消息传递基础结构。
因为ASP.NET提供了为XML Web服务内部工作的基础结构,开发者可以集中精力来实现他们的特定的XML Web服务的功能。使用ASP.NET开发一个XML Web服务从下面三步开始:
1. 创建一个带有.asmx扩展名的文件。
2. 在这个文件里面,使用一条指令声明XML Web服务。
3. 定义组成XML Web服务功能的XML Web服务方法。
XML Web服务是一个强大的技术,用于提供可通过因特网变成访问的服务。下面的建议将帮助你创建高效的XML Web服务:
XML Web服务既支持同步的又支持异步的客户端和存放XML Web服务的服务器之间的通信。在同步通信情况下,客户端发送一个对服务的请求到服务主机服务器上等待响应。这防止客户端在等待结果的时候,执行其它的操作。然而异步通信导致客户端在等待相应的时候继续处理其它的任务。客户端在可用的时候响应服务请求的结果。
当你使用Web服务描述语言工具(Wsdl.exe)来创建你的代理类的时候,它产生类中的方法的标准的、同步版本和异步版本。异步版本由两个方法组成,称为Begin和End。Begin方法用于初始化XML Web服务,而End方法取得结果。
使用异步通信能够改善系统使用率和避免客户端在它等待XML Web服务结果的时候的延迟。
下面的代码示例显示如何从一个客户应用程序产生一个到XML Web服务的异步调用。
[C#]
1@ Page Language="C#"
1@ Import Namespace="System.Net"
1<html>
2<script language="C#" runat="server">
3void EnterBtn_Click(Object Src, EventArgs E)
4{
5MyMath.Math math = new MyMath.Math();
6// Call to Add XML Web service method asynchronously
7// and then wait for it to complete.
8IAsyncResult result =
9math.BeginAdd(Convert.ToInt32(Num1.Text),
10Convert.ToInt32(Num2.Text),
11null,
12null);
13// Wait for asynchronous call to complete.
14result.AsyncWaitHandle.WaitOne();
15// Complete the asynchronous call to Add XML Web service method.
16float total = math.EndAdd(result);
17// Display results in a Label control.
18Total.Text = "Total: " + total.ToString();
19}
20</script>
21<body>
22<form action="MathClient.aspx" runat="server">
23<font face="Verdana">
24Enter the two numbers you want to add and then press
25the Total button.
26<p>
27Number 1:
28<asp:textbox id="Num1" runat="server/">
29\+
30Number 2:
31<asp:textbox id="Num2" runat="server/">
32=
33<asp:button id="Total_Button" onclick="EnterBtn_Click" runat="server/" text="Total">
34<p>
35<asp:label id="Total" runat="server/">
36</asp:label></p></asp:button></asp:textbox></asp:textbox></p></font>
37</form>
38</body>
39</html>
[Visual Basic]
1@ Page Language="VB"
1@ Import Namespace="System.Net"
1<html>
2<script language="VB" runat="server">
3Sub EnterBtn_Click(Src As Object, E As EventArgs)
4Dim math As New MyMath.Math()
5' Call to Add XML Web service method asynchronously
6' and then wait for it to complete.
7Dim result As IAsyncResult = _
8math.BeginAdd(Convert.ToInt32(Num1.Text), _
9Convert.ToInt32(Num2.Text), _
10Nothing, _
11Nothing)
12
13' Wait for asynchronous call to complete.
14result.AsyncWaitHandle.WaitOne()
15' Complete the asynchronous call to Add XML Web service method.
16Dim addtotal As Single = math.EndAdd(result)
17' Display results in a Label control.
18Total.Text = "Total: " & addtotal.ToString()
19End Sub
20</script>
21<body>
22<form action="MathClient.aspx" runat="server">
23<font face="Verdana">
24Enter the two numbers you want to add and then press
25the Total button.
26<p>
27Number 1:
28<asp:textbox id="Num1" runat="server/">
29\+
30Number 2:
31<asp:textbox id="Num2" runat="server/">
32=
33<asp:button id="Total_Button" onclick="EnterBtn_Click" runat="server/" text="Total">
34<p>
35<asp:label id="Total" runat="server/">
36</asp:label></p></asp:button></asp:textbox></asp:textbox></p></font>
37</form>
38</body>
39</html>
想获得更多关于异步通信的信息,请参阅后面的"和XML Web服务异步地通讯"。
通过因特网产生许多服务请求可能影响客户应用程序的性能。当设计你的XML Web服务时,通过创建把有关信息集中在一起的方法可以有效利用服务请求。例如,假定你有一个XML Web服务,用来检索一本书的信息。我们可以创建一个在一条服务请求中返回所有的信息的方法,来代替单独的检索书名、作者和出版社的方法。一次传送大块的信息比多次传送小块的信息更有效率。
下面的代码示例解释如何把有关信息组织到单个XML Web服务方法中。
[C#]
1@ WebService Language="C#" Class="DataService"
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
public class DataService {
[WebMethod]
public DataSet GetTitleAuthors() {
SqlConnection myConnection = new SqlConnection("Persist Security Info=False;Integrated Security=SSPI;server=localhost;database=pubs");
SqlDataAdapter myCommand1 = new SqlDataAdapter ("select * from Authors", myConnection);
SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Titles", myConnection);
DataSet ds = new DataSet();
myCommand1.Fill(ds, "Authors");
myCommand2.Fill(ds, "Titles");
return ds;
}
}
[Visual Basic]
1@ WebService Language="VB" Class="DataService"
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Public Class DataService
1<webmethod> _
2Public Function GetTitleAuthors() As DataSet
3Dim myConnection As New SqlConnection("Persist Security Info=False;Integrated Security=SSPI;server=localhost;database=pubs")
4Dim myCommand1 As New SqlDataAdapter("select * from Authors", myConnection)
5Dim myCommand2 As New SqlDataAdapter("select * from Titles", myConnection)
6Dim ds As New DataSet()
7myCommand1.Fill(ds, "Authors")
8myCommand2.Fill(ds, "Titles")
9Return ds
10End Function
11End Class
12
13当设计你的XML Web服务时,请确保使用标准的面向对象编程操作。使用封装来隐藏实现细节。对于更复杂的XML Web服务,你可以使用继承和多态性来再次使用代码并简化你的设计。
14
15下面的代码示例显示如何使用继承来创建一个执行数学计算的XML Web服务。
16
17[C#]
@ WebService Language="C#" Class="Add"
1using System;
2using System.Web.Services;
3abstract public class MathService : WebService
4{
5[WebMethod]
6abstract public float CalculateTotal(float a, float b);
7}
8public class Add : MathService
9{
10[WebMethod]
11override public float CalculateTotal(float a, float b)
12{
13return a + b;
14}
15}
16public class Subtract : MathService
17{
18[WebMethod]
19override public float CalculateTotal(float a, float b)
20{
21return a - b;
22}
23}
24public class Multiply : MathService
25{
26[WebMethod]
27override public float CalculateTotal(float a, float b)
28{
29return a * b;
30}
31}
32public class Divide : MathService
33{
34[WebMethod]
35override public float CalculateTotal(float a, float b)
36{
37if (b==0)
38return -1;
39else
40return a / b;
41}
42}
43[Visual Basic]
@ WebService Language="VB" Class="Add"
1Imports System
2Imports System.Web.Services
3MustInherit Public Class MathService : Inherits WebService
4<webmethod> _
5Public MustOverride Function CalculateTotal(a As Single, _
6b As Single) As Single
7End Class
8Public Class Add : Inherits MathService
9<webmethod> Public Overrides Function CalculateTotal(a As Single, b As Single) As Single
10Return a + b
11End Function
12End Class
13Public Class Subtract : Inherits MathService
14<webmethod> Public Overrides Function CalculateTotal(a As Single, b As Single) As Single
15Return a - b
16End Function
17End Class
18Public Class Multiply : Inherits MathService
19<webmethod> Public Overrides Function CalculateTotal(a As Single, b As Single) As Single
20Return a * b
21End Function
22End Class
23Public Class Divide : Inherits MathService
24<webmethod> Public Overrides Function CalculateTotal(a As Single, b As Single) As Single
25If b = 0 Then
26Return - 1
27Else
28Return a / b
29End If
30End Function
31End Class
32
33使用输出缓冲来改善你的XML Web服务的性能。当输出缓冲开启时,服务请求的结果被保存在输出缓冲中一段指定的时间。如果一个类似的XML Web服务请求被产生,结果可以从缓冲中取得,而不用重新计算。这样就通过减少XML Web服务服务器所需的处理来改善了XML Web服务的反馈时间。高速缓存可在客户端和服务器两者上执行。Duration属性允许你指定高速缓冲保存XML Web服务输出的时间。
34
35在客户端上使用输出高速缓冲的指令是:
@ OutputCache Duration="60"
1
2下面的代码示例显示如何在客户应用程序上使用Duration属性来指定输出高速缓冲为60秒。
3
4[C#]
@ Page Language="C#"
@ Import Namespace="System.Net"
@ OutputCache Duration="60" VaryByParam="none"
1<html>
2<script language="C#" runat="server">
3void EnterBtn_Click(Object Src, EventArgs e)
4{
5MyMath.Math math = new MyMath.Math();
6// Call the XML Web service.
7float total = math.Add(Convert.ToInt32(Num1.Text),
8Convert.ToInt32(Num2.Text));
9// Display the results in a Label control.
10Total.Text = "Total: " + total.ToString();
11}
12</script>
13<body>
14<form action="MathClient.aspx" runat="server">
15<font face="Verdana">
16Enter the two numbers you want to add and press
17the Total button.
18<p>
19Number 1:
20<asp:textbox id="Num1" runat="server/">
21\+ Number 2:
22<asp:textbox id="Num2" runat="server/">
23= <asp:button id="Total_Button" onclick="EnterBtn_Click" runat="server/" text="Total">
24<p>
25<asp:label id="Total" runat="server/">
26</asp:label></p></asp:button></asp:textbox></asp:textbox></p></font>
27</form>
28</body>
29</html>
30[Visual Basic]
@ Page Language="VB"
@ Import Namespace="System.Net"
@ OutputCache Duration="60" VaryByParam="none"
1<html>
2<script language="VB" runat="server">
3Sub EnterBtn_Click(Src As Object, e As EventArgs)
4Dim math As New MyMath.Math()
5' Call the XML Web service.
6Dim addtotal As Single = math.Add(Convert.ToInt32(Num1.Text), Convert.ToInt32(Num2.Text))
7' Display the results in a Label control.
8Total.Text = "Total: " & addtotal.ToString()
9End Sub
10</script>
11<body>
12<form action="MathClient.aspx" runat="server">
13<font face="Verdana">
14Enter the two numbers you want to add and press
15the Total button.
16<p>
17Number 1:
18<asp:textbox id="Num1" runat="server/">
19\+
20Number 2:
21<asp:textbox id="Num2" runat="server/">
22= <asp:button id="Total_Button" onclick="EnterBtn_Click" runat="server/" text="Total">
23<p>
24<asp:label id="Total" runat="server/">
25</asp:label></p></asp:button></asp:textbox></asp:textbox></p></font>
26</form>
27</body>
28</html>
29
30你还可以使用WebMethod属性类的CacheDuration属性来在服务器上允许高速缓冲。下面的代码示例显示如何在XML Web服务方法上使用CacheDuration属性来指定输出高速缓冲为60秒。
31
32[C#]
@ WebService Language="C#" Class="MathService"
1using System;
2using System.Web.Services;
3public class MathService : WebService {
4[WebMethod(CacheDuration=60)]
5public float Add(float a, float b)
6{
7return a + b;
8}
9[WebMethod(CacheDuration=60)]
10public float Subtract(float a, float b)
11{
12return a - b;
13}
14[WebMethod(CacheDuration=60)]
15public float Multiply(float a, float b)
16{
17return a * b;
18}
19[WebMethod(CacheDuration=60)]
20public float Divide(float a, float b)
21{
22if (b==0) return -1;
23return a / b;
24}
25}
26[Visual Basic]
@ WebService Language="VB" Class="MathService"
1Imports System
2Imports System.Web.Services
3Public Class MathService
4Inherits WebService
5<webmethod(cacheduration :="60)"> _
6Public Function Add(a As Single, b As Single) As Single
7Return a + b
8End Function
9
10<webmethod(cacheduration :="60)"> _
11Public Function Subtract(a As Single, b As Single) As Single
12Return a - b
13End Function
14
15<webmethod(cacheduration :="60)"> _
16Public Function Multiply(a As Single, b As Single) As Single
17Return a * b
18End Function
19
20<webmethod(cacheduration :="60)"> _
21Public Function Divide(a As Single, b As Single) As Single
22If b = 0 Then
23Return - 1
24End If
25Return a / b
26End Function
27End Class
28
29当设计你的XML Web服务时,努力遵循如何格式化模式的结构。
30
31XML Web服务使用SOAP作为主要的传送和序列化协议。一个SOAP消息由一个可选择的头体和消息体组成。头部分包含可以被Web服务器体系结构处理的信息。SOAP没有定义任何头。消息体部分包含由应用程序处理的信息,例如用于XML Web服务的参数或返回值。
32
33提供用于你的XML Web服务的文档,如一个静态HTML文件,描述你的服务的操作和数据结构。还包括如何使用这个XML Web服务的示例。不要依靠服务描述或服务帮助页面作为你唯一的文档。</webmethod(cacheduration></webmethod(cacheduration></webmethod(cacheduration></webmethod(cacheduration></webmethod></webmethod></webmethod></webmethod></webmethod></webmethod>