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

使用 WCF Web 程式設計模型開發 REST 風格 Web Service

     編輯:關於.NET

WCF 3.5 引入 Web 程式設計模型,支援以 REST 風格 設計 Web Service:以 URI 與 HTTP 協定為核心,資源具唯一識別碼,透過 HTTP 動詞(GET/POST/PUT/DELETE)操作資源。配合 UriTemplate 實現參數化 URI。本文以 Northwind 資料庫為例,示範基本開發流程。

一、定義服務契約


[ServiceContract]
public interface ICustomerService {
    [OperationContract]
    [WebGet(UriTemplate = "")]
    List<Customer> GetAllCustomers();
}
  • WebGet:指定 HTTP GET 動作
  • UriTemplate = "":不帶參數,對應基底 URI

二、實作服務


[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CustomerService : ICustomerService {
    public List<Customer> GetAllCustomers() {
        List<Customer> customerList = new List<Customer>();
        // 從資料庫讀取所有 Customer
        return customerList;
    }
}

InstanceContextMode.Single:單例模式,適合無狀態服務。

三、發布服務 (Self-Host)


ICustomerService customerService = new CustomerService();
WebServiceHost customerServiceHost = new WebServiceHost(customerService, new Uri("https://localhost:3333/"));
customerServiceHost.AddServiceEndpoint(typeof(ICustomerService), new WebHttpBinding(), "customers");
customerServiceHost.Open();
  • WebServiceHost:專為 Web 模型設計的宿主
  • WebHttpBinding:HTTP 繫結,非 SOAP
  • 端點位址:https://localhost:3333/customers

瀏覽器輸入上述網址,即回傳 XML 格式的所有客戶資料。

四、參數化查詢:UriTemplate 進階


[OperationContract]
[WebGet(UriTemplate = "{customerID}")]
Customer GetCustomer(string customerID);
  • {customerID}:參數化片段,自動繫結至方法參數
  • 請求 https://localhost:3333/customers/ALFKI → customerID = "ALFKI"

實作方法並測試,即可獲得單一客戶的 XML 回應。

五、後續擴展方向

  • 複雜 UriTemplate:多參數、查詢字串、巢狀路徑
  • WebInvoke 支援 POST/PUT/DELETE 動詞
  • JSON 格式回應(WebMessageFormat.Json)
  • 錯誤處理、快取、安全性整合

WCF Web 模型讓 .NET 開發者以熟悉的強型別介面方式,輕鬆建構符合 REST 架構風格的服務,是輕量級整合的利器。

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