Question

I want to create WCF Restful service that takes Complex Type as a parameter in Json format and return Json. I read a lots of article and examine many samples on the web. Some article suggest to add tag in Endpoint behavior and decorate Service method as below,

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

In this case, WCF returns "Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'." error message.

Another suggested way(as in this article http://dotnetmentors.com/wcf/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract.aspx) is add "" tag to Endpoint behavior instead of . But in this case IIS returns ("The remote server returned an error: (400) Bad Request.") error message.

Can you please help me how to create Restful Service that takes complex type argument in json format and return json.

Was it helpful?

Solution

This works:

[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; }
}

And self-hosting like:

var webServiceHost = new WebServiceHost(typeof(Service), 
    new Uri("http://localhost:12345"));
webServiceHost.AddServiceEndpoint(typeof(IService), new WebHttpBinding(),"");
webServiceHost.Open();

In Postman:

enter image description here

And in IIS Express with the following config:

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

Result from postman:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top