C# Web Service Howto
为项目组写了几个Howto的Case。
本文描述了一个用C#实现了在Windows Form或者Windows Console下调用Web Service的例子。 这是一个较复杂的例子。解决方案由三个项目组成:
- **ClassLibrary:**定义了两个自定义类,编译成Windows Class Library(DLL),并由另外两个项目引用
- **WebServiceHowto:**Web Service的实现,主要是一个GetStudent的WebMethod,接受一个自定义类Dorm为参数,返回另一个自定义类Student。
- **UseWebServiceHowto:**Windows Console(也可以是Windows Form),实现一个Proxy,通过添加Service Reference调用Web Service。
1. ClassLibrary Dorm.cs
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization;
namespace ClassLibrary {
public class Dorm
{
public string Name;
public string Number;
}
}
Student.cs
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization;
namespace ClassLibrary {
public class Student
{
public long Number;
public string Name;
public bool enabled;
public Dorm dorm;
}
}
2. WebServiceHowto ITSTestService.asmx.cs
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using ClassLibrary;
namespace WebServiceHowto { /// /// Summary description for ITSTestService ///
public class ITSTestService : System.Web.Services.WebService
{
public string HelloWorld()
{
return "Hello World";
}
public Student GetStudent(Dorm d)
{
Student student = new Student();
student.dorm = d;
student.enabled = true;
student.Number = 222222;
student.Name = "maojun";
return student;
}
}
}
3. UseWebServiceHowto Program.cs
using System; using System.Collections.Generic; using System.Text; using ClassLibrary;
namespace UseWebServiceHowto { class Program { static void Main(string[] args) { WebServiceProxy proxy = new WebServiceProxy(); Dorm dorm = new Dorm();
dorm.Name = "geng der drom";
dorm.Number = "16-501-5";
Student s = proxy.GetStudent(dorm);
Console.WriteLine("Student Name={0}, Dorm={1}", s.Name, s.dorm.Name);
}
}
}
WebServiceProxy.cs
using System; using System.Collections.Generic; using System.Text; using System.Web.Services.Protocols; using System.Web.Services; using System.Diagnostics; using System.ComponentModel; using ClassLibrary;
namespace UseWebServiceHowto {
class WebServiceProxy : SoapHttpClientProtocol
{
public WebServiceProxy()
{
base.Url = "http://localhost:3489/ITSTestService.asmx";
}
public Student GetStudent(Dorm d)
{
return (Student)base.Invoke("GetStudent", new object[] { d });
}
}
}
下载:用Visual Studio 2008打开 http://download.nocoo.us/Download/Archive/CSharpHowto/SQLServer.rar