HelloWCF。IService1.cs、Service1.cs。Student[DataContract]
public class Student
{
[DataMember] public int Id { get; set; }
[DataMember] public string Name { get; set; }
[DataMember] public int Age { get; set; }
}
IStudentService[ServiceContract]
public interface IStudentService
{
[OperationContract] void AddStudent(Student s);
[OperationContract] void DeleteStudent(int id);
[OperationContract] List<Student> GetAllStudents();
}
StudentServicepublic class StudentService : IStudentService
{
static readonly List<Student> _repo = new List<Student>();
public void AddStudent(Student s) => _repo.Add(s);
public void DeleteStudent(int id) => _repo.RemoveAll(s => s.Id == id);
public List<Student> GetAllStudents() => _repo;
}
App.config → 編輯 WCF 設定。Service1,新增 HelloWCF.StudentService (指向編譯後的 DLL)。Contract = HelloWCF.IStudentService、Binding = wsHttpBinding (或 basicHttpBinding)。Binding = mexHttpBinding、Contract = IMetadataExchange,啟用中繼資料發佈。serviceMetadata httpGetEnabled="true",並關聯至服務。IStudentService 三個方法。AddStudent(),輸入參數 (Id=1, Name=Tom, Age=20) → Invoke。GetAllStudents() → Invoke,Response 面板顯示剛新增的學生清單。| 現象 | 可能原因 | 解決 |
|---|---|---|
| Test Client 顯示舊合約 | App.config 未更新 | 重新「編輯 WCF 設定」指向新 DLL |
| 無法新增服務參考 | MEX 端點未啟用 | 檢查 mexHttpBinding 端點與 serviceMetadata |
| 跨機器呼叫失敗 | 防火牆阻擋 Port | 開放 8732/8733 或自訂 Port |
Binding 選擇:basicHttpBinding (相容)、wsHttpBinding (WS-* 標準)、netTcpBinding (內網高效能)、netNamedPipeBinding (同機器極速)。IErrorHandler 統一例外轉 FaultException。WebHttpBinding 建立 RESTful API。WCF 理論雖繁雜,但工具鏈 (SvcHost + Test Client) 讓「先動手、再深究」成為最佳學習策略。建立第一個可跑通的服務,後續擴充才有依據。