使用WEB服务:
在客户机处创建一个ASP.NET WEB应用程序,在aspx文件中添加如下代码:
<form id="Form1" method="post" runat="server">
<asp:Label Runat="server" ID="resultLabel" /><br>
<asp:Button Runat="server" ID="triggerButton" Text="HelloWorld" />
</form>
右击TestClient1解决方案,添加WEB引用,输入刚才发布的WEB服务的地址如: http://localhost/TestSrv1/Services1.asmx,点击添加引用,再在命名空间处添加
using TestClient1.localhost.
返回图形设计页面,双击按钮,在aspx.cs文件中添加如下代码:
private void triggerButton_Click(object sender, System.EventArgs e)
{
Service1 myService = new Service1();
resultLabel.Text = myService.HelloWorld();
}
编译运行即可看到效果,点击按钮试试.
接下来看一个较实用的例子----查询Northwind中的定单信息
创建步骤同上,服务器端添加的方法如下:
[WebMethod]
public DataSet GetOrderData(Int32 intOrderID)
{
System.Data.SqlClient.SqlConnection sqlConn;
System.Data.SqlClient.SqlDataAdapter daOrder;
DataSet ds;
sqlConn = new System.Data.SqlClient.SqlConnection();
sqlConn.ConnectionString = @"server=localhost;database=Northwind;UID=sa;PWD=sa;";
sqlConn.Open();
daOrder = new System.Data.SqlClient.SqlDataAdapter("select * from Orders where OrderID="+intOrderID,sqlConn);
ds = new DataSet();
daOrder.Fill(ds,"Orders");
sqlConn.Close();
return ds;
}
客户端的aspx文件主要代码如下:
<form id="Form1" method="post" runat="server">
<FONT face="宋体">Order ID:<asp:TextBox Runat="server" ID="orderidquery" /><br>
<asp:Button Runat="server" ID="query" Text="Query" /><br>
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 8px;
POSITION: absolute; TOP: 152px" runat="server"
Width="336px" Height="112px"></asp:DataGrid>
</FONT>
</form>
aspx.cs 中的按钮响应代码如下:
private void query_Click(object sender, System.EventArgs e)
{
int intOrderid;
intOrderid = int.Parse(orderidquery.Text);
Service1 OrderService = new Service1();
DataSet OrderData = new DataSet();
DataTable t = new DataTable();
OrderData = OrderService.GetOrderData(intOrderid);
t = OrderData.Tables["Orders"];
DataGrid1.DataSource = t;
DataGrid1.DataBind();
}
具体细节应参考HelloWorld示例的结构进行斟酌.
本文只是简单地介绍WEB服务的开发,读者可以根据实际要求开发功能强大的服务供客户使用.
本文地址:http://com.8s8s.com/it/it42663.htm