WCF返回JSON的詳細配置

來源:互聯網
上載者:User

標籤:

開發環境:VS2008,c#

1.建立個WCF服務網站

檔案-建立-網站-WCF服務

2,運行一下,提示配置WEB.CONFIG,點擊確認.

3,開啟web.config增加如下節點:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
  </serviceHostingEnvironment>

 endpoint 中增加 behaviorConfiguration="webBehavior"

<endpointBehaviors>
    <behavior name="webBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>

處理完以上3處之後,web.config就OK了.

4,IService.cs 增加:

[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    List<CompositeType> Test();

Service.cs 增加:

public List<CompositeType> Test()
    {
        List<CompositeType> lst = new List<CompositeType>();
        CompositeType type = new CompositeType();
        type.BoolValue = true;
        type.StringValue = "22";
        lst.Add(type);
        CompositeType type2 = new CompositeType();
        type2.BoolValue = false;
        type2.StringValue = "33";
        lst.Add(type2);
        return lst;
    }

CompositeType類:

[DataContract]

public class CompositeType

{     bool boolValue = true;     string stringValue = "Hello ";

    [DataMember]    

public bool BoolValue     {         get { return boolValue; }         set { boolValue = value; }     }

    [DataMember]    

public string StringValue     {         get { return stringValue; }         set { stringValue = value; }     }

}

5,Service.cs 增加

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

6,運行測試,如:

http://localhost:1177/WCFData/Service.svc

手動輸入:http://localhost:1177/WCFData/Service.svc/Test

返回:[{"BoolValue":true,"StringValue":"22"},{"BoolValue":false,"StringValue":"33"}]

測試成功!

WCF返回JSON的詳細配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.