次の方法で共有


WCF Web HTTP の書式設定

WCF Web HTTP プログラミング モデルを使用すると、サービス操作が応答を返す最適な形式を動的に決定できます。 適切な形式を決定するための 2 つの方法として、自動と明示的の 2 つの方法がサポートされています。

自動書式設定

有効にすると、自動書式設定によって、応答を返す最適な形式が選択されます。 次の順序でチェックすることで、最適な形式が決定されます。

  1. 要求メッセージの Accept ヘッダーのメディアの種類。

  2. 要求メッセージのコンテンツ タイプ。

  3. 操作の既定の書式設定。

  4. 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 の場合、開発者はFormatXmlまたは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);  
    }  
}  

こちらも参照ください