共用方式為


進階 Web 程式設計

這個範例會示範一些 Windows Communication Foundation (WCF) Web 程式設計模型的進階功能。本範例提出下列概念:

  • URI Template Dispatch:允許將服務作業繫結至符合指定之模式的外部 URI。
  • HTTP Methods:可以使用任意 HTTP 方法 (包括 GET、PUT、POST 和 DELETE) 叫用服務作業。
  • HTTP Headers:服務可以使用 WebOperationContext 操作 HTTP 標頭的內容。
Bb472541.note(zh-tw,VS.90).gif注意:
要建置和執行這個範例,必須安裝 .NET Framework version 3.5。要開啟專案和方案檔,必須要有 Visual Studio 2008。

此範例會實作客戶資料的基本集合,並儲存於記憶體中。它支援基本的 Create, ReadUpdateDelete 作業,並使用 URI 和 HTTP 方法對外公開這些作業。

服務合約和實作

在這個範例中,服務會實作接聽基底 URI 位址 (https://localhost:8000/Customers) 的單一端點。服務以下列方式處理前置底下的 URI 要求:

  • 對 https://localhost:8000/Customers 的 GET 要求會路由到 GetCustomers()
  • 系統中的每個客戶都有唯一識別項,而在 URI 裡會附帶這個識別項。這些 URI (例如,https://localhost:8000/Customers/1) 的 GET 要求會對應至 GetCustomer()
  • 對個別客戶的 URI 發出 HTTP PUT 要求,可以更新該客戶。
  • 對客戶的 URI 發出 HTTP DELETE,可以將客戶從系統移除。
  • 對基底 URI 發出 HTTP POST,可以將新資料新增至系統。
[ServiceContract]
public interface ICustomerCollection
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "")]
    Customer AddCustomer(Customer customer);

    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "{id}")]
    void DeleteCustomer(string id);

    [OperationContract]
    [WebGet(UriTemplate = "{id}")]
    Customer GetCustomer(string id);

    [OperationContract]
    [WebGet(UriTemplate = "")]
    List<Customer> GetCustomers();

    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "{id}")]
    Customer UpdateCustomer(string id, Customer newCustomer);
}

服務合約是由 Service 類別所實作,而此類別會使用 WCF 單一執行個體。接收到的所有要求都會路由至伺服器上的同一個物件執行個體,讓要求之間可以共用客戶的雜湊資料表。

[ServiceBehavior( InstanceContextMode = InstanceContextMode.Single )]
public class Service : ICustomerCollection
{
   Hashtable customers = new Hashtable();
   ...
}        

對服務基底 URI (例如,https://localhost:8000/Customers) 發出 HTTP GET 要求可以叫用 GetCustomers() 作業。Customer 型別會透過Data Contract Serializer序列化。

public List<Customer> GetCustomers()
{
    List<Customer> list = new List<Customer>();

    foreach (Customer c in this.customers.Values)
    {
        list.Add(c);
    }

    return list;
}

對個別客戶的唯一 URI 發出 GET 要求,可以擷取該客戶。例如,可以在 https://localhost:8000/Customers/1 擷取 ID 為 1 的客戶。同樣地,可以在 http:/localhost:8000/Customers/2 存取客戶 2。這兩個 URI 都會分派至伺服器上的 GetCustomer(string id) 方法。套用在 GetCustomer() 作業合約的 [WebGet( UriTemplate="{id}")] 屬性會建立這種對應。UriTemplate 是一個用來描述 GetCustomer() 作業要處理之一組 URI 的模式。在本例中,這個模式描述所有剛好有一個片段在端點基底位址後面的 URI。這個片段的內容與 {id} 範本變數相符,且由 WCF 發送器傳遞至方法的 id 參數。

//[WebGet( UriTemplate=”{id}” )]
public Customer GetCustomer(string id)
{
    Customer c = this.customers[id] as Customer;
      
    if (c == null)
    {
        WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
        return null;
    }

    return c;
}

GetCustomer() 的實作會查詢客戶識別碼 (在 URI 中提供),然後傳回相關聯的客戶。如果找不到客戶,作業便會使用 WebOperationContext 方法設定回應狀態碼,以傳回 HTTP 404 回應。

請注意,跟 GetCustomer() 方法一樣,UpdateCustomer()DeleteCustomer() 方法也會與相同的 URI 範本產生關聯。WCF Web 程式設計模型允許將多項作業繫結至同一個 URI 範本,只要這些作業各自關聯於不同的 HTTP 方法即可。在本例中,UpdateCustomer() 方法繫結至 HTTP PUT 方法,而 DeleteCustomer() 作業則是繫結至 HTTP DELETE 方法。

[OperationContract]
[WebInvoke( Method="PUT", UriTemplate="{id}")]
Customer UpdateCustomer(string id, Customer newCustomer);

[OperationContract]
[WebInvoke( Method="DELETE", UriTemplate="{id}" )]
void DeleteCustomer(string id);

AddCustomer() 方法示範如何使用新的 UriTemplate 類別,來建立符合特定模式的新 URI。WebOperationContext() 方法可用來將 HTTP CREATED 回應與設為新建客戶之 URI 的 location 標頭一起傳回。

public Customer AddCustomer(Customer customer)
{
    lock (writeLock)
    {
        counter++;
        UriTemplateMatch match = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

        UriTemplate template = new UriTemplate("{id}");
        customer.Uri = template.BindByPosition(match.BaseUri, counter.ToString());

        customers[counter.ToString()] = customer;
        WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(customer.Uri);
    }

    return customer;
}

服務裝載

使用 WebServiceHost() 來裝載服務,並使用 WebHttpBinding() 公開一個端點。

using (WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("https://localhost:8000/Customers")))
{
    //WebServiceHost will automatically create a default endpoint at the base address using the WebHttpBinding
    //and the WebHttpBehavior, so there's no need to set it up explicitly
    host.Open();
    ...
}

用戶端

用戶端會使用 WebChannelFactory 方法建立,以建立遠端服務的通道。

using (WebChannelFactory<ICustomerCollection> cf = new WebChannelFactory<ICustomerCollection>( baseAddress ))
{
    //WebChannelFactory will default to using the WebHttpBinding with the WebHttpBehavior,
    //so there's no need to set up the endpoint explicitly
    ICustomerCollection channel = cf.CreateChannel();
    ...
}

使用通道的用戶端會向管理客戶集合狀態的伺服器發出一連串的要求。

輸出

使用 POST 新增一些客戶:

Alice 123 Pike Place https://localhost:8000/Customers/1
Bob 2323 Lake Shore Drive https://localhost:8000/Customers/2

使用 PUT 更新客戶:

Charlie 123 Pike Place https://localhost:8000/Customers/1

使用 GET 擷取客戶的清單:

Charlie 123 Pike Place https://localhost:8000/Customers/1
Bob 2323 Lake Shore Drive https://localhost:8000/Customers/2

使用 DELETE 刪除客戶:

最終的客戶清單:

Charlie 123 Pike Place https://localhost:8000/Customers/1

當互動完成時,程式會等候您按下按鍵,然後終止。

若要設定、建置及執行範例

  1. 請確定您已執行 Windows Communication Foundation 範例的單次安裝程序

  2. 若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例中的指示。

  3. 若要在單一或跨電腦的組態中執行本範例,請遵循執行 Windows Communication Foundation 範例中的指示。

請參閱

工作

基本 Web 程式設計模型範例

Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.