1、建立项目WebService和WinForm项目,这里起名为WinFormInvokeWebService.
如图所示:
2、Service1.asmx代码为:(这部分其实和上篇的代码是一样的)
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data;
namespace WebService1
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
//无参方法
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
//有参方法1
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}
//有参方法2
[WebMethod]
public int Sum(int x)
{
int sum = 0;
for (int i = 0; i <= x; i++)
{
sum += i;
}
return sum;
}
// 返回一个复合类型
[WebMethod]
public Student GetStudentByStuNo(string stuNo)
{
if (stuNo == "001")
return new Student { StuNo = "001", StuName = "张三" };
if (stuNo == "002")
return new Student { StuNo = "002", StuName = "李四" };
return null;
}
//返回返回泛型集合的
[WebMethod]
public List<Student> GetList()
{
List<Student> list = new List<Student>();
list.Add(new Student() { StuNo = "001", StuName = "张三" });
list.Add(new Student() { StuNo = "002", StuName = "李四" });
list.Add(new Student() { StuNo = "003", StuName = "王五" });
return list;
}
//返回DataSet
[WebMethod]
public DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("StuNo", Type.GetType("System.String"));
dt.Columns.Add("StuName", Type.GetType("System.String"));