2012-03-07 36 views
1

我想實現一個非常簡單的WCF服務,返回JSON。我現在嘗試了6個小時,但仍然無法工作。我希望你能幫助我解決這個問題。WCF的JSON實現

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.Serialization; 

namespace Tcf.AtX.Services 
{ 
    [DataContract] 
    public class Person 
    { 
     [DataMember] 
     public string Name { get; set; } 
    } 
} 

服務合同

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ServiceModel; 
using System.ServiceModel.Web; 

namespace Tcf.AtX.Services 
{ 
    [ServiceContract] 
    public interface IBroadcastService 
    { 
     /// <summary> 
     /// Broadcasts the specified message. 
     /// </summary> 
     /// <param name="message">The message.</param> 
     /// <returns></returns> 
     [OperationContract] 
     [WebInvoke(Method="GET", ResponseFormat= WebMessageFormat.Json)] 
     Person Broadcast(string message); 
    } 
} 

服務實現

​​

配置

<?xml version="1.0"?> 
<configuration> 

    <system.web> 
    <compilation debug="true"/> 
    </system.web> 
    <system.serviceModel> 
    <services> 
     <service name="Tcf.AtX.Services.BroadcastService"> 
     <endpoint address="" binding="webHttpBinding" contract="Tcf.AtX.Services.IBroadcastService" behaviorConfiguration="json"/> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://localhost:8732/Design_Time_Addresses/Tcf.AtX.Services/BroadcastService/" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="json"> 
      <webHttp /> 
     </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
     <behavior name=""> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="false" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration> 

的問題是,我沒有看到測試客戶端內的服務,所以我不能測試我的方法。 我也自己寫了一個測試客戶端,但是當我將它引用到我的項目中時,我無法創建我的服務實例。

有人可以請我解釋我做錯了什麼?

最好的問候,

羅布

回答

3

測試客戶端並不對非SOAP端點工作(即一個你有,它使用的WebHttpBinding)。嘗試簡單地創建試圖撥打以下

WebClient c = new WebClient(); 
Console.WriteLine(
    c.DownloadString(
     "http://localhost:8732/Design_Time_Addresses/Tcf.AtX.Services/Broadcast?message=MyMessage")); 

還有一件事你必須操作,如代碼一些程序,你需要的[WebInvoke(Method="GET")]屬性更改爲[WebGet]

+0

好的,我會試試看。添加Web引用不起作用。我只獲取名稱空間並且無法創建服務的實例 – 2012-03-07 17:58:58

+0

是的,出於與測試客戶端不起作用相同的原因。非SOAP端點不公開其元數據,因此這些工具(測試客戶端,添加引用)不知道如何使用這些端點。 – carlosfigueira 2012-03-07 22:59:34

+0

好的,很高興知道!我想知道....我需要一個web服務,所以我可以在我的Mono for Android應用程序中使用它,但這是做到這一點的優先方式嗎? – 2012-03-08 12:32:12