Peter
Peter

Reputation: 5342

Getting A Type-Specific Response From A WCF REST Generic Request?

I am designing a WCF REST service. A requirement for the design is that the client is unaware of the particulars of a given request. For example, the following request:

https://www.domain.com/dashboard/group/id/0

Would return:

Request: GetGroup(GroupId = 0)
Response: 
{
Title="Country",
children = 
{
title="USA", Id=1, type=GROUP},
{title="England", Id=2, type=GROUP}
}
}

And the following request:

https://www.domain.com/dashboard/group/id/3

Would return:

Request: GetGroup(groupId = 3)
Response: 
{
Title="Customers",
children = 
{
title="General Motors", Id=1, type=CUSTOMER},
{title="General Electric", Id=2, type=CUSTOMER}
}
}

MY QUESTION IS how do I take a generic REST request and return a type-specific response?

In my project, there are a few Types that will be serialized in the JSON response. The serialized object depends on the passed-in groupId parameter. They are:

GROUP
CUSTOMER
FACILITY
TANK

In a related post, it was suggested that I create a base class that exposes GetGroupById and the above classes should override the base class method. If this sounds like a good example of how to attack this problem, I'd appreciate an example. Or, alternatively, other suggestions.

Thanks in advance.

Upvotes: 1

Views: 1006

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245479

You could always create a service that returns a Stream and use the JsonSerializer to serialize your objects into a MemoryStream, and then return the MemoryStream from the service:

public Stream GetSomeObject(int groupId)
{
    byte[] bytes;
    var serializer = new JavaScriptSerializer();

    switch(groupId)
    {
        case 2:
            var groups = GetGroups(); // fill the groups however
            bytes = Encoding.UTF8.GetBytes(serializer.Serialize(groups));
            break;
        case 3:
            var customers = GetCustomers();
            bytes = Encoding.UTF8.GetBytes(serializer.Serialize(customers));
            break;
    }

    return new MemoryStream(bytes);
}

In that case, you would simply load the appropriate object into memory based on the parameters and return the appropriate strongly typed object via the Stream.

This is the same approach I've used in the past to return Json results from a WCF Service without the type information (the approach was suggested by a member Microsoft's WCF team, so I figured it was fairly reliable).

Upvotes: 1

Related Questions