Matt Cashatt
Matt Cashatt

Reputation: 24218

How do I make use of a WCF service response without setting up a data contract?

Background

I have inherited a project which relies on several different WCF "mex" endpoints for it's data. The goal of my particular project, once complete, is to serve as an API layer which calls these legacy WCF services, manipulates the returned objects (in rare cases only), serializes to JSON and then responds Restfully to the requesting client.

C#, MVC 4, .NET 4.

I am very experienced with RESTful web services, but NOT with WCF.

Here is an example of an endpoint uri:

http://product.sqa.acme.com/products.svc/mex

Question

In setting up my first class that consumes one of these WCF services, it appears that I have to set up an entire data contract in order to use the returned object. Is this correct? If this is not correct, how do I call a method of the WCF interface (i.e. IProductService >> GetProductById(123)) and then manipulate the resulting object without a contract?

I have tried this:

var ip = (IProductService)new ProductServiceClient("http://product.sqa.acme.com/product.svc/mex");
            var product = ip.GetProductById("DVP4963619");

But the code fails because a contract is not found. Since 90% of what I will be doing is simply passing-through a request and then serializing the response to JSON, it seems like overkill to have to define a contract for every service call I make. Any help is appreciated.

Thanks,

Matt

Upvotes: 1

Views: 863

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87273

To consume the service, you can just point Visual Studio's Add Service Reference wizard to the "mex" endpoint that you have, and it will generate a client for you, including the data contract classes for that.

To create the (REST) service that returns data, you have two choices. You can either create the data contracts representing the data you want to return (or reuse the ones generated by the tool). Or you can bypass those, if you want to control the output of the operation entirely. If the operation returns a Stream type, you can write anything (JSON or not) to the output (by returning a subclass of that abstract type), so you wouldn't have to create a data contract for that. You can find more this "raw mode" at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx.

Another alternative for returning data would be to use something like ASP.NET Web API, which does have support for "untyped JSON" model using the JSON.NET types in the Newtonsoft.Json.Linq namespace.

Upvotes: 3

Related Questions