WCF Web HTTP 程式設計模型可讓您動態判斷服務作業傳回其回應的最佳格式。 支援判斷適當格式的兩種方法:自動和明確。
自動格式化
啟用時,自動格式化會選擇傳回回應的最佳格式。 它會依序檢查下列項目來判斷最佳格式:
要求訊息的 Accept 標頭中的媒體類型。
要求訊息的內容類型。
作業中的預設格式設定。
WebHttpBehavior 中的預設格式設定。
如果要求訊息包含 Accept 標頭,Windows Communication Foundation (WCF) 基礎結構會搜尋支援的類型。 如果Accept
標頭指定媒體類型的優先順序,則會依其優先順序處理。 如果在標頭中 Accept
找不到適當的格式,則會使用要求訊息的內容類型。 如果未指定適當的內容類型,則會使用作業的預設格式設定。 預設格式是使用 ResponseFormat
和 WebGetAttribute 屬性的參數WebInvokeAttribute來設定。 如果未在作業上指定預設格式,則會使用 屬性的值 DefaultOutgoingResponseFormat 。 自動格式化依賴 AutomaticFormatSelectionEnabled 屬性。 當此屬性設定為 true
時,WCF 基礎結構會決定要使用的最佳格式。 預設會停用自動格式選取,以提供回溯相容性。 您可以透過程式設計方式或透過設定來啟用自動格式選取。 下列範例示範如何在程式碼中啟用自動格式選取。
// This code assumes the service name is MyService and the service contract is IMyContract
Uri baseAddress = new Uri("http://localhost:8000");
WebServiceHost host = new WebServiceHost(typeof(MyService), baseAddress)
try
{
ServiceEndpoint sep = host.AddServiceEndpoint(typeof(IMyContract), new WebHttpBinding(), "");
// Check it see if the WebHttpBehavior already exists
WebHttpBehavior whb = sep.Behaviors.Find<WebHttpBehavior>();
if (whb != null)
{
whb.AutomaticFormatSelectionEnabled = true;
}
else
{
WebHttpBehavior webBehavior = new WebHttpBehavior();
webBehavior.AutomaticFormatSelectionEnabled = true;
sep.Behaviors.Add(webBehavior);
}
// Open host to start listening for messages
host.Open();
// ...
}
catch(CommunicationException ex)
{
Console.WriteLine("An exception occurred: " + ex.Message());
}
您也可以透過設定來啟用自動格式設定。 您可以直接在 AutomaticFormatSelectionEnabled 上設定 WebHttpBehavior 屬性,或使用 WebHttpEndpoint。 下列範例示範如何在 上 WebHttpBehavior啟用自動格式選取。
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp automaticFormatSelectionEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<!-- the "" standard endpoint is used by WebServiceHost for auto creating a web endpoint. -->
<standardEndpoint name="" helpEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
下列範例示範如何使用 WebHttpEndpoint 來啟用自動格式選擇。
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<!-- the "" standard endpoint is used by WebServiceHost for auto creating a web endpoint. -->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
明確格式設定
顧名思義,在明確格式化中,開發人員會決定在作業程序代碼內使用的最佳格式。 如果最佳格式是 XML 或 JSON,開發人員會將 設定 Format 為 Xml 或 Json。 Format如果未明確設定 屬性,則會使用作業的預設格式。
下列範例會檢查格式查詢字串參數,以取得要使用的格式。 如果已指定,則會使用 Format來設定作業的格式。
public class Service : IService
{
[WebGet]
public string EchoWithGet(string s)
{
// if a format query string parameter has been specified, set the response format to that. If no such
// query string parameter exists the Accept header will be used
string formatQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (!string.IsNullOrEmpty(formatQueryStringValue))
{
if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase))
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
}
else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase))
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
}
else
{
throw new WebFaultException<string>($"Unsupported format '{formatQueryStringValue}'", HttpStatusCode.BadRequest);
}
}
return "You said " + s;
}
如果您需要支援除 XML 或 JSON 外的格式,請定義您的操作,使其具有 Message 作為傳回類型。 在作業程式代碼中,判斷要使用的適當格式,然後使用下列其中一種方法建立 Message 物件:
WebOperationContext.CreateAtom10Response
WebOperationContext.CreateJsonResponse
WebOperationContext.CreateStreamResponse
WebOperationContext.CreateTextResponse
WebOperationContext.CreateXmlResponse
每個方法都會接受內容,並建立具有適當格式的訊息。
WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements
方法可用來取得用戶端慣用的格式清單,以遞減喜好設定的順序。 下列範例示範如何使用 WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements
來判斷要使用的格式,然後使用適當的 create 回應方法來建立回應消息。
public class Service : IService
{
public Message EchoListWithGet(string list)
{
List<string> returnList = new List<string>(list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
IList<ContentType> acceptHeaderElements = WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements();
for (int x = 0; x < acceptHeaderElements.Count; x++)
{
string normalizedMediaType = acceptHeaderElements[x].MediaType.ToLowerInvariant();
switch (normalizedMediaType)
{
case "image/jpeg": return CreateJpegResponse(returnList);
case "application/xhtml+xml": return CreateXhtmlResponse(returnList);
case "application/atom+xml": return CreateAtom10Response(returnList);
case "application/xml": return CreateXmlResponse(returnList);
case "application/json": return CreateJsonResponse(returnList);
}
}
// Default response format is XML
return CreateXmlResponse(returnList);
}
}