具有复杂类型参数的WebInvoke不适用于Json端点

时间:2014-05-09 09:28:08

标签: c# json web-services wcf rest

我想创建WCF Restful服务,它将Complex Type作为Json格式的参数并返回Json。我阅读了很多文章并在网上查看了很多样本​​。有些文章建议在Endpoint行为中添加标签并装饰Service方法,如下所示,

[WebInvoke(UriTemplate = "/PlaceOrder", 
        RequestFormat= WebMessageFormat.Json,   
        ResponseFormat = WebMessageFormat.Json, Method = "POST")]

在这种情况下,WCF返回"Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'."错误消息。

另一种建议方式(如本文http://dotnetmentors.com/wcf/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract.aspx中所述)是将“”标记添加到Endpoint行为而不是。但在这种情况下,IIS返回(“远程服务器返回错误:(400)错误请求。”)错误消息。

你能帮我解决一下如何创建以json格式获取复杂类型参数并返回json的Restful Service。

1 个答案:

答案 0 :(得分:5)

这有效:

[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();

邮递员:

enter image description here

在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>

邮递员的结果:

enter image description here