从WCF Web服务返回JSON

时间:2011-08-11 14:41:02

标签: wcf json

我正在尝试从WCF Web服务返回JSON,但是当我访问URL时,我得到的都是错误的请求。

这是界面:

 [ServiceContract]
    public interface IHighWCFService
    {
        [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "KnownZombies")]
        [WebInvoke(Method = "GET")]
        List<ZombieInfo> GetZombies(); 

        [OperationContract]
        void DoWork();
    }

以下是上述界面的实现:

public class HighWCFService : IHighWCFService
    {
        public void DoWork()
        {
            throw new NotImplementedException();
        }

        public List<ZombieInfo> GetZombies()
        {
            var zombies = new List<ZombieInfo>()
                              {
                                  new ZombieInfo() {FirstName = "John", LastName = "Doe"},
                                  new ZombieInfo() {FirstName = "Mohammad", LastName = "Azam"}
                              };
            return zombies; 
        }
    }

    [DataContract]
    public class ZombieInfo
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }
    }

我访问以下网址,导致400次错误请求:

http://localhost:22059/HighWCFService.svc/KnownZombies

Web.Config看起来像这样:

<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="HighOnCodingWebApps.HighWCFServiceBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="HighOnCodingWebApps.HighWCFServiceBehavior"
    name="HighOnCodingWebApps.HighWCFService">
    <endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="HighOnCodingWebApps.IHighWCFService">
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="IMetadataExchange" />
   </service>
  </services>
 </system.serviceModel>

1 个答案:

答案 0 :(得分:0)

两件事:

  • 我认为一个400错误的请求错误是由一些其他无关的问题所产生的 到JSON。
  • 我还认为你必须在列表中序列化该列表 因为您没有使用SOAP,所以为了接收它们而使用JSON对象 了。您可以使用此课程DATACONTRACTJSONSERIALIZER