如何:从 Web 服务客户端进行异步调用
下面的代码示例演示如何从客户端应用程序对 Web 服务进行异步调用。 此示例阐释了使用 ASP.NET 创建的 XML Web services 的设计准则主题中阐述的准则之一。
安全 注意: |
---|
此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。 默认情况下,ASP.NET 网页会验证用户输入是否不包括脚本或 HTML 元素。 有关更多信息,请参见Script Exploits Overview。 |
示例
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<html>
<script language="C#" runat="server">
void EnterBtn_Click(Object Src, EventArgs E)
{
MyMath.Math math = new MyMath.Math();
// Call to Add Web service method asynchronously
// and then wait for it to complete.
IAsyncResult result =
math.BeginAdd(Convert.ToInt32(Num1.Text),
Convert.ToInt32(Num2.Text),
null,
null);
// Wait for asynchronous call to complete.
result.AsyncWaitHandle.WaitOne();
// Complete the asynchronous call to Add Web service method.
float total = math.EndAdd(result);
// Display results in a Label control.
Total.Text = "Total: " + total.ToString();
}
</script>
<body>
<form action="MathClient.aspx" runat=server>
<font face="Verdana">
Enter the two numbers you want to add and then press
the Total button.
<p>
Number 1:
<asp:textbox id="Num1"
runat=server/>
+
Number 2:
<asp:textbox id="Num2"
runat=server/>
=
<asp:button id="Total_Button"
text="Total"
OnClick="EnterBtn_Click"
runat=server/>
<p>
<asp:label id="Total" runat=server/>
</font>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Net" %>
<html>
<script language="VB" runat="server">
Sub EnterBtn_Click(Src As Object, E As EventArgs)
Dim math As New MyMath.Math()
' Call to Add Web service method asynchronously
' and then wait for it to complete.
Dim result As IAsyncResult = _
math.BeginAdd(Convert.ToInt32(Num1.Text), _
Convert.ToInt32(Num2.Text), _
Nothing, _
Nothing)
' Wait for asynchronous call to complete.
result.AsyncWaitHandle.WaitOne()
' Complete the asynchronous call to Add Web service method.
Dim addtotal As Single = math.EndAdd(result)
' Display results in a Label control.
Total.Text = "Total: " & addtotal.ToString()
End Sub
</script>
<body>
<form action="MathClient.aspx" runat=server>
<font face="Verdana">
Enter the two numbers you want to add and then press
the Total button.
<p>
Number 1:
<asp:textbox id="Num1"
runat=server/>
+
Number 2:
<asp:textbox id="Num2"
runat=server/>
=
<asp:button id="Total_Button"
text="Total"
OnClick="EnterBtn_Click"
runat=server/>
<p>
<asp:label id="Total" runat=server/>
</font>
</form>
</body>
</html>
请参见
任务
如何:使用等待技术实现异步 Web 服务客户端
如何:使用回调技术实现异步 Web 服务客户端
概念
使用 ASP.NET 创建的 XML Web services 的设计准则
与 XML Web services 进行异步通信
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。