2

我正在开发一个返回此的 WCF Web 服务:

{
    "allFormsResult": [
        {
            "FormId": 1,
            "FormName": "Formulario 1"
        },
        {
            "FormId": 2,
            "FormName": "Formulario 2"
        },
        {
            "FormId": 3,
            "FormName": "Formulario 3"
        }
    ]
}

这是代码:

public class RestServiceImpl : IRestServiceImpl
    {
        public List<FormContract> allForms()
        {
            List<FormContract> list = null;
            using (var vAdmEntities = new ADMDatabase.ADMEntities())
            {
                list = new List<FormContract>();
                foreach (var form in vAdmEntities.Form)
                {
                    FormContract formC = new FormContract
                    {
                        FormName = form.name.Trim(),
                        FormId = form.formId
                    };
                    list.Add(formC);
                }
            }

            return list;
        }
    }

我该怎么做才能以这种方式生成它?

[
    {
        "FormId": 1,
        "FormName": "Formulario 1"
    },
    {
        "FormId": 2,
        "FormName": "Formulario 2"
    },
    {
        "FormId": 3,
        "FormName": "Formulario 3"
    }
]
4

2 回答 2

4

问题在这里:

namespace ADM
{
    [ServiceContract]
    public interface IRestServiceImpl
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "forms/")]
        List<FormContract> allForms();
    }
}

我必须这样使用它:

namespace ADM
{
    [ServiceContract]
    public interface IRestServiceImpl
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "forms/")]
        List<FormContract> allForms();
    }
}

改变BodyStyle

BodyStyle = WebMessageBodyStyle.Bare
于 2012-04-09T13:43:17.997 回答
0

此行为也可以通过 Web.Config 设置为默认值,无需直接将属性添加到合约中。

<services>
  <service name="MyServiceNameSpace.MyServiceClass">
    <endpoint
        address="http://yourservicedomain.ext/MyServiceClass.svc/"
        binding="webHttpBinding"
        contract="MyServiceNameSpace.MyServiceContract"
        behaviorConfiguration="MyEndpointBehavoir"
        listenUri="/" />        
  </service>      
</services>

<behaviors>
  <endpointBehaviors>
    <behavior name="MyEndpointBehavoir">
      <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Bare"/>
    </behavior>        
  </endpointBehaviors>
</behaviors>
于 2015-03-23T16:29:32.240 回答