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:單例模式,適合無狀態服務。
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 繫結,非 SOAPhttps://localhost:3333/customers瀏覽器輸入上述網址,即回傳 XML 格式的所有客戶資料。
[OperationContract]
[WebGet(UriTemplate = "{customerID}")]
Customer GetCustomer(string customerID);
{customerID}:參數化片段,自動繫結至方法參數https://localhost:3333/customers/ALFKI → customerID = "ALFKI"實作方法並測試,即可獲得單一客戶的 XML 回應。
UriTemplate:多參數、查詢字串、巢狀路徑WebInvoke 支援 POST/PUT/DELETE 動詞WebMessageFormat.Json)WCF Web 模型讓 .NET 開發者以熟悉的強型別介面方式,輕鬆建構符合 REST 架構風格的服務,是輕量級整合的利器。