我想创建 WCF Restful 服务,它将复杂类型作为 Json 格式的参数并返回 Json。我阅读了很多文章并检查了网络上的许多示例。一些文章建议在端点行为中添加标签并装饰服务方法,如下所示,
[WebInvoke(UriTemplate = "/PlaceOrder",
RequestFormat= WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
在这种情况下,WCF 返回 “使用‘UriTemplate’的终结点不能与‘System.ServiceModel.Description.WebScriptEnablingBehavior’一起使用。” 错误消息。
另一种建议的方法(如本文 http://dotnetmentors.com/wcf/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract.aspx 中所述)是将“”标记添加到端点行为而不是 .但在这种情况下,IIS 会返回(“远程服务器返回错误:(400) 错误请求。”)错误消息。
能否请您帮助我如何创建采用 json 格式的复杂类型参数并返回 json 的 Restful 服务。
请您参考如下方法:
这个有效:
[ServiceContract]
public interface IService
{
[WebInvoke(Method = "POST", UriTemplate = "/ModifyCustomer", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Customer ModifyCustomer(Customer customer);
}
public class Service : IService
{
public Customer ModifyCustomer(Customer customer)
{
customer.Age += 1;
return customer;
}
}
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
自托管如:
var webServiceHost = new WebServiceHost(typeof(Service),
new Uri("http://localhost:12345"));
webServiceHost.AddServiceEndpoint(typeof(IService), new WebHttpBinding(),"");
webServiceHost.Open();
在 postman 中:
在 IIS Express 中使用以下配置:
<system.serviceModel>
<services>
<service name="RestServiceTest.Service" behaviorConfiguration="myServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="RestServiceTest.IService" behaviorConfiguration="myEndpointBehavior">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="myServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="myEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
postman 的结果:
