2011-08-18 67 views
2

Gentelmens,WCF和JSON问题

我正在使用WCF服务,我希望看到JSON结果。 但我没有任何想法如何做到这一点。我已经标记为我的方法

[WebGet(ResponseFormat = WebMessageFormat.Json)] 

但这并不帮助我。在“Wcf测试客户端”中,我将结果看作xml。

我已尝试添加行为(WebHttp使用JSON)到终点,但我有错误:

The endpoint at 'http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/' does not have a Binding 
with the None MessageVersion. 'System.ServiceModel.Description.WebHttpBehavior' is only intended for use 
with WebHttpBinding or similar bindings. 

DataContract:

[DataContract] 
    public class Foo 
    { 
    [DataMember] 
    public string Name { get; set; } 
    } 

接口:

[ServiceContract] 
    public interface IFooService 
    { 
    [OperationContract] 
    List<Foo> GetList(); 
    } 

服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class FooSerivce : IFooService 
    { 
    [WebGet(ResponseFormat = WebMessageFormat.Json)] 
    public List<Foo> GetList() 
    { 
     return new List<Foo> {new Foo {Name = "Name1"}, new Foo {Name = "Name2"}}; 
    } 
    } 

Web.config文件:

<system.serviceModel> 
    <services> 
     <service name="PlayingWithWCF2.FooSerivce"> 
     <endpoint address="" behaviorConfiguration="" binding="wsHttpBinding" 
     contract="PlayingWithWCF2.IFooService"> 
      <identity> 
      <dns value="localhost" /> 
      </identity> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name=""> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="false" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 

能给我一些建议我该如何解决这个问题?

P.S.对不起,如果问题是愚蠢的,但我是新手在WCF

回答

3

要返回JSON,您必须使用WCF测试客户端不支持的REST服务。您已将服务定义为支持REST,但未将其配置为公开REST端点。您需要此配置:

<system.serviceModel> 
    <services> 
     <service name="PlayingWithWCF2.FooSerivce"> 
     <endpoint address="webHttp" binding="webHttpBinding" contract="PlayingWithWCF2.IFooService" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:8732/PlayingWithWCF2/Service1/" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="webHttp"> 
      <webHttp /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    </system.serviceModel> 
+0

感谢您的回答,但我有问题。如何在没有WCF测试客户端的情况下测试我的REST服务。我应该添加WCF服务应用程序并将其用于测试吗? – ukraine

+0

您可以使用测试应用程序,您可以使用Web浏览器来测试GET请求,并且您可以使用Fiddler或任何其他合适的工具来测试GET,POST和其他请求。 –

0

我相信你的问题在于你的web.config,你的绑定配置应该设置为webHttp。 看看下面的question/answer上的计算器