在测试(1)的代码 中增加其它的自定义Web方法,然后演示如何调用该方法。
1. 增加一个简单加法
[WebMethod\]
public int Sum(int a, int b)
{
return a + b;
}
运行Web Service ,该功能可以正常调用。
调用测试:
输出值正常。
2. 创建一个返回值为DataTable对象数据
`
DataTable dt = new DataTable();
[WebMethod\]
public string Get\_Products()
{
dt.Columns.Add("ProductName");
dt.Columns.Add("Cost");
dt.Rows.Add("Rluer", 200);
dt.Rows.Add("Pen", 120);
dt.Rows.Add("PenBox", 300);
dt.Rows.Add("ColorPen", 210);
return JsonConvert.SerializeObject(dt);
}
`
需要将DataTable对象序列化为Json字符串。需要添加引用 Microsoft.AspNet.WebApi.client组件
添加引用后,后台代码:
using Newtonsoft.Json;
测试运行:
3. 创建一个App添加WebService的引用
添加服务引用
输入服务器地址,转到。可重新命名命名空间,也可使用默认名称。
添加Web引用
可默认名称,也可改变名称:
后台代码添加引用:
using Newtonsoft.Json;
using System.Data;
创建服务的实例:
localhost.MyWebService myService = new localhost.MyWebService();
在窗口加载事件中:
private void Window\_Loaded(object sender, RoutedEventArgs e)
{
var results = myService.Get\_Products();
DataTable dt = JsonConvert.DeserializeObject<DataTable>(results);
dg.ItemsSource = dt.DefaultView;
}
效果如下:
使用Web Service 功能OK。