WCF Web HTTP biçimlendirmesi

WCF Web HTTP programlama modeli, bir hizmet işleminin yanıtını döndürmesi için en iyi biçimi dinamik olarak belirlemenize olanak tanır. Uygun biçimi belirlemeye yönelik iki yöntem desteklenir: otomatik ve açık.

Otomatik biçimlendirme

Etkinleştirildiğinde, otomatik biçimlendirme yanıtın döndürüleceği en iyi biçimi seçer. Aşağıdakileri sırayla denetleyerek en iyi biçimi belirler:

  1. İstek iletisinin Accept üst bilgisindeki medya türleri.

  2. İstek iletisinin içerik türü.

  3. İşlemdeki varsayılan biçim ayarı.

  4. Web'de varsayılan biçim ayarıHttpBehavior.

İstek iletisi bir Accept üst bilgisi içeriyorsa, Windows Communication Foundation (WCF) altyapısı desteklediği bir tür arar. Accept Üst bilgi, medya türleri için öncelikleri belirtirse, bunlar kabul edilir. Üst bilgide Accept uygun bir biçim bulunmazsa, istek iletisinin içerik türü kullanılır. Uygun bir içerik türü belirtilmezse, işlem için varsayılan biçim ayarı kullanılır. Varsayılan biçim ve WebInvokeAttribute özniteliklerinin WebGetAttribute parametresiyle ResponseFormat ayarlanır. İşlemde varsayılan bir biçim belirtilmezse, özelliğinin DefaultOutgoingResponseFormat değeri kullanılır. Otomatik biçimlendirme özelliğine AutomaticFormatSelectionEnabled bağlıdır. Bu özellik olarak trueayarlandığında, WCF altyapısı kullanılacak en iyi biçimi belirler. Geriye dönük uyumluluk için otomatik biçim seçimi varsayılan olarak devre dışıdır. Otomatik biçim seçimi program aracılığıyla veya yapılandırma aracılığıyla etkinleştirilebilir. Aşağıdaki örnekte kodda otomatik biçim seçiminin nasıl etkinleştirileceği gösterilmektedir.

// 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());  
  }  

Otomatik biçimlendirme, yapılandırma aracılığıyla da etkinleştirilebilir. özelliğini doğrudan üzerinde WebHttpBehavior veya kullanarak WebHttpEndpointayarlayabilirsinizAutomaticFormatSelectionEnabled. Aşağıdaki örnekte, üzerinde otomatik biçim seçiminin nasıl etkinleştirileceği gösterilmektedir 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>  

Aşağıdaki örnekte kullanılarak WebHttpEndpointotomatik biçim seçiminin nasıl etkinleştirileceği gösterilmektedir.

<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>  

Açık biçimlendirme

Adından da anlaşılacağı gibi, açık biçimlendirmede geliştirici işlem kodu içinde kullanılacak en iyi biçimi belirler. En iyi biçim XML veya JSON ise geliştirici ya da XmlJsonolarak ayarlarFormat. Format Özellik açıkça ayarlanmadıysa, işlemin varsayılan biçimi kullanılır.

Aşağıdaki örnek, kullanılacak bir biçim için format sorgu dizesi parametresini denetler. Belirtilmişse, kullanarak Formatişlemin biçimini ayarlar.

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 veya JSON dışındaki biçimleri desteklemeniz gerekiyorsa, dönüş türüne Messagesahip olmak için işleminizi tanımlayın. İşlem kodunda, kullanılacak uygun biçimi belirleyin ve ardından aşağıdaki yöntemlerden birini kullanarak bir Message nesne oluşturun:

  • WebOperationContext.CreateAtom10Response

  • WebOperationContext.CreateJsonResponse

  • WebOperationContext.CreateStreamResponse

  • WebOperationContext.CreateTextResponse

  • WebOperationContext.CreateXmlResponse

Bu yöntemlerin her biri içeriği alır ve uygun biçime sahip bir ileti oluşturur. yöntemi, WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements tercihi azaltmak için istemci tarafından tercih edilen biçimlerin listesini almak için kullanılabilir. Aşağıdaki örnekte, kullanılacak biçimi belirlemek için nasıl kullanılacağı WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements ve ardından yanıt iletisini oluşturmak için uygun yanıt oluşturma yönteminin nasıl kullanılacağı gösterilmektedir.

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);  
    }  
}  

Ayrıca bkz.