共用方式為


WebContentTypeMapper 範例

WebContentTypeMapper 範例示範如何將新的內容類型對應至 Windows Communication Foundation (WCF) 訊息本文格式。

WebHttpEndpoint 元素會插入在 Web 訊息編碼器中,讓 WCF 在相同的端點上接收 JSON、XML 或原始二進位訊息。 此編碼器會藉由尋找要求的 HTTP 內容型別來判定訊息的本文格式。 這個範例會介紹 WebContentTypeMapper 類別,以允許使用者控制內容型別與本文格式之間的對應。

WCF 會為內容類型提供一組預設對應。 例如,application/json 會對應至 JSON,而 text/xml 會對應至 XML。 未對應至 JSON 或 XML 的任何內容型別都會對應至原始二進位格式。

在某些案例中 (例如,Push-Style API),服務開發人員不會控制由用戶端傳回的內容型別。 例如,用戶端可能會以 text/javascript 方式傳回 JSON,而不是以 application/json 方式。 在這種情況中,服務開發人員必須提供衍生自 WebContentTypeMapper 的型別來正確地處理指定的內容型別,如下列範例程式碼所示。

public class JsonContentTypeMapper : WebContentTypeMapper
{
    public override WebContentFormat
               GetMessageFormatForContentType(string contentType)
    {
        if (contentType == "text/javascript")
        {
            return WebContentFormat.Json;
        }
        else
        {
            return WebContentFormat.Default;
        }
    }
}

此型別必須覆寫 GetMessageFormatForContentType(String) 方法。 此方法必須評估 contentType 引數,並傳回下列其中一個值:JsonXmlRawDefault。 傳回的 Default 會延後至預設的 Web 訊息編碼器對應。 在先前的範例程式碼中,text/javascript 內容型別會對應至 JSON,而所有其他對應都維持不變。

若要使用 JsonContentTypeMapper 類別,請在 Web.config 中使用以下內容:

<system.serviceModel>
  <standardEndpoints>
    <webHttpEndpoint>
      <standardEndpoint name="" contentTypeMapper="Microsoft.Samples.WebContentTypeMapper.JsonContentTypeMapper, JsonContentTypeMapper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </webHttpEndpoint>
  </standardEndpoints>
</system.serviceModel>

若要確認使用 JsonContentTypeMapper 的需求,從以上的組態檔中移除 contentTypeMapper 屬性。 嘗試使用 text/javascript 傳送 JSON 內容時,無法載入用戶端頁面。

若要安裝、建置及執行範例

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

  2. 依照建置 Windows Communication Foundation 範例所述,建置解決方案 WebContentTypeMapperSample.sln。

  3. 瀏覽至 http://localhost/ServiceModelSamples/JCTMClientPage.htm (請勿使用瀏覽器從專案目錄開啟 JCTMClientPage.htm)。