WebContentTypeMapper 範例示範如何將新的內容類型對應至 Windows Communication Foundation (WCF) 訊息本文格式。
元素 WebHttpEndpoint 會插入 Web 訊息編碼器,讓 WCF 在相同的端點接收 JSON、XML 或原始二進位訊息。 編碼器會藉由查看要求的 HTTP 內容類型來判斷訊息的本文格式。 此範例介紹 類別 WebContentTypeMapper ,可讓使用者控制內容類型與本文格式之間的對應。
WCF 會為內容類型提供一組預設對應。 例如, application/json
對應至 JSON,並 text/xml
對應至 XML。 未對應至 JSON 或 XML 的任何內容類型,會對應至原始二進位格式。
在某些案例中,服務開發人員不會控制用戶端傳回的內容類型。例如,推送樣式 API。 例如,用戶端可能會將 JSON 傳回為 text/javascript
,而不是 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
並傳回下列其中一個值: Json、 Xml、 Raw或 Default。 傳回 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 內容時,用戶端頁面無法載入。
要設定、建置和執行範例,請執行以下步驟:
請確定您已針對 Windows Communication Foundation 範例 執行One-Time 安裝程式。
如 建置 Windows Communication Foundation 範例中所述,建置解決方案WebContentTypeMapperSample.sln。
流覽至
http://localhost/ServiceModelSamples/JCTMClientPage.htm
(請勿在瀏覽器中從專案目錄內開啟 JCTMClientPage.htm)。