2009-11-17 17 views
17

Bir WCF hizmetinde kullanılan bir yöntemi açıklayan bir ServiceContract var. Yöntem, bir UriTemplate ve ResponseFormat tanımlayan bir WebGet özniteliğine sahiptir.WCF OperationContract yönteminin WebGet özniteliği birden çok ResponseFormat türüne sahip olabilir mi?

Tek bir yöntemi yeniden kullanmak ve farklı UriTemplates ve farklı ResponseFormats ile birden çok WebGet özniteliğine sahip olmak istiyorum. Temelde, XML türüne karşılık JSON gibi dönüş türlerini ayırt etmek için birden fazla yönteme sahip olmaktan kaçınmayı umuyorum. Şimdiye kadar gördüğüm tüm örneklerde, her WebGet özniteliği için farklı bir yöntem oluşturmam gerekiyor.

[ServiceContract] 
public interface ICatalogService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "product/{id}/details?format=xml", ResponseFormat = WebMessageFormat.Xml)] 
    [WebGet(UriTemplate = "product/{id}/details?format=json", ResponseFormat = WebMessageFormat.Json)] 
    Product GetProduct(string id); 
} 

yüzden bunu başarmak için bir yol var mı: İşte böyle xml ve json dönüş türleri her ikisi için içinCategoryConfigurationnesne kullanmak istiyorum Yukarıdaki örneğe

[ServiceContract] 
public interface ICatalogService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "product/{id}/details?format=xml", ResponseFormat = WebMessageFormat.Xml)] 
    Product GetProduct(string id); 

    [OperationContract] 
    [WebGet(UriTemplate = "product/{id}/details?format=json", ResponseFormat = WebMessageFormat.Json)] 
    Product GetJsonProduct(string id); 
} 

OperationContract örneği verilmiştir Farklı ResponseFormat'ları döndürmek için farklı yöntemler yazmam mümkün değil mi?

Teşekkürler!

cevap

12

Bu

[ServiceContract] 
public interface ICatalogService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "product/{id}/details?format={format}")] 
    Stream GetProduct(string id, string format); 
} 

yapabilirsiniz Sonra kodunuzu kolu serileştirmesini parametre üzerinde belirtilen değeri kapalı tabanlı.

XML için Serileştirmenizi işleyen bir yardımcı yöntem yazın. yöntem benim için çalıştı altında

public static Stream GetServiceStream(string format, string callback, DataTable dt, SyndicationFeed sf) 
     { 
      MemoryStream stream = new MemoryStream(); 
      StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); 
      if (format == "xml") 
      { 
       XmlSerializer xmls = new XmlSerializer(typeof(DataTable)); 
       xmls.Serialize(writer, dt); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
      } 
      else if (format == "json") 
      { 
       var toJSON = new JavaScriptSerializer(); 
       toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() }); 
       writer.Write(toJSON.Serialize(dt)); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/json"; 
      } 
      else if (format == "jsonp") 
      { 
       var toJSON = new JavaScriptSerializer(); 
       toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() }); 
       writer.Write(callback + "(" + toJSON.Serialize(dt) + ");"); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/json"; 
      } 
      else if (format == "rss") 
      { 
       XmlWriter xmlw = new XmlTextWriter(writer); 
       sf.SaveAsRss20(xmlw); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
      } 
      else if (format == "atom") 
      { 
       XmlWriter xmlw = new XmlTextWriter(writer); 
       sf.SaveAsAtom10(xmlw); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
      } 
      else 
      { 
       writer.Write("Invalid formatting specified."); 
       WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; 
      } 

      writer.Flush(); 
      stream.Position = 0; 
      return stream; 
     } 
} 
8

Ben Yanlış hatırlamıyorsam: json hizmeti için

Sözleşme:

[ServiceContract] 
public interface IServiceJson { 
    [OperationContract()] 
    [WebGet(UriTemplate = "Operation/?param={param}", 
         ResponseFormat = WebMessageFormat.Json)] 
    ReturnType Operation(string param); 
} 

xml hizmeti için İrtibat: her ikisi için

[ServiceContract] 
public interface IServiceXml { 
    [OperationContract(Name = "OperationX")] 
    [WebGet(UriTemplate = "Operation/?param={param}", 
         ResponseFormat = WebMessageFormat.Xml)] 
    ReturnType Operation(string param); 
} 

Uygulama:

public class ServiceImplementation : IServiceJson, IServiceXml { 
    ReturnType Operation(string param) { 
    // Implementation 
    } 
} 

Ve web.config yapılandırma (json ve xml yanıtları not bitiş noktaları):

<system.serviceModel> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="webHttp"> 
      <webHttp /> 
     </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
     <behavior name="serviceBehaviour"> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <services> 
     <service behaviorConfiguration="serviceBehaviour" name="ServiceImplementation"> 
     <endpoint address="json/" behaviorConfiguration="webHttp" binding="webHttpBinding" 
     bindingConfiguration="webHttpBindingSettings" contract="IServiceJson"> 
      <identity> 
      <dns value="localhost" /> 
      </identity> 
     </endpoint> 
     <endpoint address="xml/" behaviorConfiguration="webHttp" binding="webHttpBinding" 
     bindingConfiguration="webHttpBindingSettings" contract="IServiceXml"> 
      <identity> 
      <dns value="localhost" /> 
      </identity> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     </service> 
    </services> 
    <bindings> 
     <webHttpBinding> 
     <binding name="webHttpBindingSettings"> 
      <readerQuotas maxStringContentLength="5000000"/> 
     </binding> 
     </webHttpBinding> 
    </bindings> 
    </system.serviceModel> 

Şimdi hizmetinizi arayabilirsiniz: json yanıtı: http://yourServer/json/Operation/?param=value xml cevabı: http://yourServer/xml/Operation/?param=value

(Üzgünüm, yukarıdaki kodda herhangi bir hata varsa, doğrulama için çalıştırmamıştım).

İlgili konular