首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# WCF 入門實戰:用 VS2010 建立、設定與測試服務 (圖文教學)

     編輯:關於C語言

專案建立

  1. Visual Studio 2010 → 新增專案 → WCF 服務程式庫。
  2. 專案名稱:HelloWCF。
  3. 刪除預設產生的 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();
}

服務實作 StudentService

public 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 視覺化設定 (重點)

  1. 右鍵 App.config → 編輯 WCF 設定。
  2. 服務:移除舊的 Service1,新增 HelloWCF.StudentService (指向編譯後的 DLL)。
  3. 端點:
    • 端點 1:Contract = HelloWCF.IStudentService、Binding = wsHttpBinding (或 basicHttpBinding)。
    • 端點 2 (MEX):Binding = mexHttpBinding、Contract = IMetadataExchange,啟用中繼資料發佈。
  4. 服務行為:新增 serviceMetadata httpGetEnabled="true",並關聯至服務。
  5. 存檔 (Ctrl+S)。

啟動與測試

  1. 按 F5 啟動,會出現兩個視窗:
    • 系統匣 WCF Service Host (WcfSvcHost.exe) — 承載服務。
    • WCF Test Client (WcfTestClient.exe) — 內建測試工具。
  2. 測試客戶端左側樹狀圖會顯示 IStudentService 三個方法。
  3. 雙擊 AddStudent(),輸入參數 (Id=1, Name=Tom, Age=20) → Invoke。
  4. 雙擊 GetAllStudents() → Invoke,Response 面板顯示剛新增的學生清單。

常見問題排查

現象可能原因解決
Test Client 顯示舊合約App.config 未更新重新「編輯 WCF 設定」指向新 DLL
無法新增服務參考MEX 端點未啟用檢查 mexHttpBinding 端點與 serviceMetadata
跨機器呼叫失敗防火牆阻擋 Port開放 8732/8733 或自訂 Port

進階學習路徑

  • 掌握 Binding 選擇:basicHttpBinding (相容)、wsHttpBinding (WS-* 標準)、netTcpBinding (內網高效能)、netNamedPipeBinding (同機器極速)。
  • 實作 IErrorHandler 統一例外轉 FaultException。
  • 嘗試 Self-host (Console App / Windows Service) 脫離 IIS。
  • 探索 WebHttpBinding 建立 RESTful API。

結語

WCF 理論雖繁雜,但工具鏈 (SvcHost + Test Client) 讓「先動手、再深究」成為最佳學習策略。建立第一個可跑通的服務,後續擴充才有依據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved