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

Learn WCF (3) 開發 WCF 客戶端程式:三種建立 Proxy 方式完整比較與實作

     編輯:關於.NET

開發 WCF 客戶端有三種主流方式:Visual Studio「加入服務參考」、命令列工具 svcutil.exe、手工程式碼撰寫。本文逐一實作並比較優缺點。

方式一:Visual Studio 加入服務參考 (最常用)

  1. 右鍵專案 →「加入服務參考」
  2. 輸入服務 URL:https://localhost:39113/WCFServiceText/WCFStudentText.svc
  3. 指定命名空間 (如 ServiceReference1),確定

加入服務參考對話框

自動完成:下載 WSDL、產生 Proxy 類別 (實作服務合約)、產生 App.config/Web.config 客戶端區段。

搭配 ObjectDataSource 無程式碼繫結

<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" ... />
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    TypeName="ServiceReference1.WCFStudentText" SelectMethod="GetStudent" />
  • TypeName:Proxy 類別完整名稱 (含命名空間)
  • SelectMethod:Proxy 方法名稱
  • 優點:零程式碼、宣告式、適合簡單查詢畫面

方式二:svcutil.exe 命令列工具 (自動化/建置整合首選)

svcutil.exe https://localhost:39113/WCFServiceText/WCFStudentText.svc

svcutil.exe 執行畫面

產出檔案:

  • WCFStudentServiceClient.cs:Proxy 類別原始碼
  • Web.config / output.config:客戶端配置

將兩檔案加入專案,修改 ObjectDataSource 的 TypeName 指向新 Proxy 類別即可使用。適合 CI/CD 流程自動化產生 Proxy。

方式三:手工撰寫 Proxy 程式碼 (完全控制/學習用)

根據 svcutil.exe 產出的 Proxy 碼手工複製修改。Proxy 類別繼承 ClientBase<TChannel> 並實作服務合約,提供 5 個建構函式多載:

public partial class StuServiceContractClient : ClientBase<IStuServiceContract>, IStuServiceContract
{
    public StuServiceContractClient() { }
    public StuServiceContractClient(string endpointConfigurationName) : base(endpointConfigurationName) { }
    public StuServiceContractClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { }
    public StuServiceContractClient(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { }
    public StuServiceContractClient(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { }

    public void AddStudent(Student stu) => base.Channel.AddStudent(stu);
    public Student[] GetStudent() => base.Channel.GetStudent();
}
  • endpointConfigurationName:對應 <client><endpoint name="..."> 的 name
  • remoteAddress:可覆寫配置檔中的位址
  • Binding / EndpointAddress:完全程式化控制

三種方式比較總結

方式優點缺點適用場景
VS 加入參考視覺化、自動同步、IntelliSense專案耦合、大型專案重新產生慢一般開發、快速原型
svcutil.exe可自動化、無 VS 依賴、版本控管友善需手動加入專案、更新需重跑CI/CD、團隊協作、自動化建置
手工程式碼完全控制、理解內部機制維護成本高、易出錯學習、特殊動態需求、極簡部署
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved