我正在开发一个返回此内容的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"
}
]
答案 0 :(得分: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
答案 1 :(得分: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>