[VS2010] WCF 4.0 新功能 (3): 由 REST 服務中傳回自訂的格式

[VS2010] WCF 4.0 新功能 (3): 由 REST 服務中傳回自訂的格式

在前一回的 REST API 服務實作中,我們已經可以傳回一組 XML 的資料給用戶端,但是有時候我們要的不是 XML,有可能是一般文字 (plain text),RSS feed 資料或是 JSON 格式的資料,那這時候要怎麼做呢?我們可以利用 System.ServiceModel.Channel 的 Message 類別,在 REST 服務的方法中,傳回 Message 物件,例如下列的服務合約:

[ServiceContract(Namespace = "http://sample.azure.com/appfabric/servicebus/productcontract")]
public interface IProductQuery
{
    [OperationContract, WebGet]
    List<ProductInfo> LookupProducts();
    [OperationContract, WebGet(UriTemplate = "Products/{ProductID}")]
    ProductInfo LookupProduct(string ProductID);
    [OperationContract, WebInvoke(Method = "POST", UriTemplate = "Products/Post", BodyStyle = WebMessageBodyStyle.Bare)]
    string HandlePostData(Stream input);
  
[OperationContract, WebGet(UriTemplate = "CustomFormatProducts")]
    Message LookupProductsWithCustomFormat();
}

 

在 LookupProductsWithCustomFormat() 函式中,我們傳回一個 Message 物件,這個物件在 WCF 輸出時會建立不同的 Message 格式,而服務要利用 WebOperationContext 物件的幾個方法來生成它,包含幾個內建的訊息:

  • WebOperationContext.CreateJsonResponse() : 生成 JSON 訊息。
  • WebOperationContext.CreateAtom10Response() : 生成 ATOM 1.0 的 Feed 格式。
  • WebOperationContext.CreateTextResponse() : 生成文字格式訊息。
  • WebOperationContext.CreateStreamResponse() : 生成訊息資料流格式訊息。
  • WebOperationContext.CreateXmlResponse() : 生成 XML 訊息格式,這是預設的訊息格式。

例如下列的方法實作,會傳回 JSON 的訊息:

public Message LookupProductsWithCustomFormat()
{
    List<ProductInfo> products = new List<ProductInfo>();

    using (NorthwindEntities context = new NorthwindEntities())
    {
        var query = from q in context.Products
                    select q;

        if (query.Count() > 0)
        {
            foreach (var item in query)
                products.Add(new ProductInfo() { Name = item.ProductName, ProductID = item.ProductID });
        }
    }

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
    Message resultMessage = WebOperationContext.Current.CreateJsonResponse<List<ProductInfo>>(products);

    return resultMessage;
}

這個方法會輸出下列訊息:

[{"Name":"Chai","ProductID":1},{"Name":"Chang","ProductID":2},{"Name":"Aniseed Syrup","ProductID":3},{"Name":"Chef Anton's Cajun Seasoning","ProductID":4},{"Name":"Chef Anton's Gumbo Mix","ProductID":5} … ]

參考資料:

Returning Custom Formats from WCF WebHttp Services