2013-01-11 30 views
0

我有一個需要返回JSON/JSONP的WCF 4.5服務。我可以通過使用WebScriptServiceHostFactory來完成此操作,但它會將__type特殊屬性添加到所有對象中,並將響應包裝在{d:{...}}對象中。我不想那樣。帶有JSONP但不具有特殊屬性的WCF

我可以通過使用WebServiceHostFactory來擺脫它,但不支持JSONP。

如何從WCF實現乾淨的JSONP輸出?

回答

0

你的函數/方法有這些屬性嗎?

<OperationContract()> _ 
<WebGet(UriTemplate:="GetJobDetails?inpt={inpt}", BodyStyle:=WebMessageBodyStyle.Wrapped, 
     RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)> 
+0

這些屬性不會影響是否支持JSONP。 – carlosfigueira

0

你有幾個選項來啓用JSONP與的WebHttpBinding用法:

如果你想使用WebServiceHostFactory,你可以在默認端點更改默認值的crossDomainScriptAccessEnabled財產由該工廠創建。這可以通過添加以下部分,你的配置來完成:

<system.serviceModel> 
    <standardEndpoints> 
     <webHttpEndpoint> 
      <standardEndpoint crossDomainScriptAccessEnabled="true" 
           defaultOutgoingResponseFormat="Json"/> 
     </webHttpEndpoint> 
    </standardEndpoints> 
</system.serviceModel> 

如果您不希望更改默認所有 Web服務主機在您的應用程序,那麼你可以讓你的應用程序中的變化只要。一種選擇是使用自定義的服務主機工廠,將根據需要設置終點:

public class MyFactory : ServiceHostFactory 
    { 
     protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) 
     { 
      return new MyServiceHost(serviceType, baseAddresses); 
     } 

     class MyServiceHost : ServiceHost 
     { 
      public MyServiceHost(Type serviceType, Uri[] baseAddresses) 
       : base(serviceType, baseAddresses) 
      { 
      } 

      protected override void OnOpening() 
      { 
       // this assumes the service contract is the same as the service type 
       // (i.e., the [ServiceContract] attribute is applied to the class itself; 
       // if this is not the case, change the type below. 
       var contractType = this.Description.ServiceType; 
       WebHttpBinding binding = new WebHttpBinding(); 
       binding.CrossDomainScriptAccessEnabled = true; 
       var endpoint = this.AddServiceEndpoint(contractType, binding, ""); 
       var behavior = new WebHttpBehavior(); 
       behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json; 
       endpoint.Behaviors.Add(behavior); 
      } 
     } 
    } 

而另一種替代方案是通過配置來定義端點:

<system.serviceModel> 
    <services> 
     <service name="StackOverflow_14280814.MyService"> 
      <endpoint address="" 
         binding="webHttpBinding" 
         bindingConfiguration="withJsonp" 
         behaviorConfiguration="web" 
         contract="StackOverflow_14280814.MyService" /> 
     </service> 
    </services> 
    <bindings> 
     <webHttpBinding> 
      <binding name="withJsonp" crossDomainScriptAccessEnabled="true" /> 
     </webHttpBinding> 
    </bindings> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior name="web"> 
       <webHttp/> 
      </behavior> 
     </endpointBehaviors> 
    </behaviors> 
</system.serviceModel> 
+0

< webHttp/>對我們很重要。 – lcryder