2014-12-05 129 views
0

我有以下服務:WCF REST服務返回空類

[ServiceContract] 
    interface IConnectionService 
    { 
     [OperationContract] 
     [WebInvoke(Method = "POST", UriTemplate = "GetState", BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped), Description("")] 
     State GetState(); 
    } 

    [DataContract] 
    public class State 
    { 
     [DataMember] 
     public bool Client_1_Ok { get; set; } 

     [DataMember] 
     public bool Client_2_Ok { get; set; } 
    } 

在我的服務器端創建國家類的新實例,並設置變量只是爲了看看他們到達客戶端,因爲它是應該

public class Server : IConnectionService 
    { 
     public State GetState() 
     { 
      State tempState = new State(); 

      tempState .Client_1_Ok = true; 
      tempState .Client_2_Ok = true; 

      return tempState ; 
     } 

的客戶端我打開一個通道,並調用GETSTATE我的服務器端..到目前爲止好

 private IConnectionService ConnectionChannel = null; 

     public State GetState() 
     { 
      try 
      { 
       ConnectionFactory = new WebChannelFactory<IConnectionService>(new Uri("http://" + this.HostIpAddress + ":" + this.Port.ToString() + "/Tes")); 
       this.ConnectionChannel = ConnectionFactory.CreateChannel(); 

       State returnvalue = this.ConnectionChannel.GetState(); 

       return state; 
      } 
      catch (Exception e) 
      { 
       //Communication error 
       return null; 
      } 
      finally 
      { 
       try { this.ConnectionChannel.Close(); } 
       catch { this.ConnectionChannel.Abort(); } 

       //dispose of the connection channel 
       this.ConnectionChannel.Dispose(); 
       this.ConnectionChannel = null; 
      } 
     } 

但客戶端的GetState調用總是返回布爾值爲false的狀態實例。

在類似的帖子peaople忘記添加DataContract和DataMember屬性,但我一定要添加這些。解決方案可能是小而笨的,但我看不到我弄亂了什麼地方

+0

您是否已經配置重新審視基礎上:http://stackoverflow.com/questions/15910199/wcf-rest -service-not-returning-data-in-browser? – 2014-12-05 15:43:54

+2

爲什麼這是GET POST? – 2014-12-05 15:46:28

回答

0

servicecontract沒有RequestFormat。在我的情況下,它需要WebMessageFormat.Json

我的ServiceContract現在看起來是這樣的:

[ServiceContract] 
    interface IConnectionService 
    { 
     [WebGet(UriTemplate = "GetState", BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json), Description("")] 
     State GetState(); 
    }