Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Rest parameters involving complex types

Tags:

rest

xml

wcf

Setting up a WCF service that uses the webHttpBinding... I can return complex types from the method as XML ok. How do I take in a complex type as a parameter?

[ServiceContract(Name = "TestService", Namespace = "http://www.test.com/2009/11")]
public interface ITestService
{
    [OperationContract]
    [WebInvoke(Method = "POST", 
               BodyStyle = WebMessageBodyStyle.Bare, 
               UriTemplate = "/Person/{customerAccountNumber}, {userName}, {password}, {PersonCriteria}")]
    Person SubmitPersonCriteria(string customerAccountNumber, 
                                string userName, 
                                string password, 
                                PersonCriteria details);
}

Since the UriTemplate only allows strings, what's the best practice? The idea is the client app will post a request to the service like search criteria for a person. The service will respond with the appropriate object containing the data as XML.

like image 896
Excelsior Avatar asked Nov 10 '09 17:11

Excelsior


1 Answers

You can post complex types using rest.

[ServiceContract]
public interface ICustomerSpecialOrderService
{    
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "deletecso/")]
    bool DeleteCustomerOrder(CustomerSpecialOrder orderToDelete);
}

The implementation looks like this:

public bool DeleteCustomerOrder(CustomerSpecialOrder orderToDelete)
{
    // Do something to delete the order here.
}

You can call a method from a WPF client:

public void DeleteMyOrder(CustomerSpecialOrder toDelete)
{
    Uri address = new Uri(your_uri_here);
    var factory = new WebChannelFactory<ICustomerSpecialOrderService>(address);
    var webHttpBinding = factory.Endpoint.Binding as WebHttpBinding;
    ICustomerSpecialOrderService service = factory.CreateChannel();
    service.DeleteCustomerOrder(toDelete);
}

Or you can call it with a HttpWebRequest as well, writing the complex type to a byte array which we do from a mobile client.

private HttpWebRequest DoInvokeRequest<T>(string uri, string method, T requestBody)
{
    string destinationUrl = _baseUrl + uri;
    var invokeRequest = WebRequest.Create(destinationUrl) as HttpWebRequest;
    if (invokeRequest == null)
        return null;

    // method = "POST" for complex types
    invokeRequest.Method = method;
    invokeRequest.ContentType = "text/xml";

    byte[] requestBodyBytes = ToByteArray(requestBody);
    invokeRequest.ContentLength = requestBodyBytes.Length;


    using (Stream postStream = invokeRequest.GetRequestStream())
        postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);

    invokeRequest.Timeout = 60000;

    return invokeRequest;
}
like image 80
Brett Bim Avatar answered Sep 28 '22 02:09

Brett Bim