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.
You could always create a service that returns a Stream and use the
JsonSerializerto serialize your objects into aMemoryStream, and then return theMemoryStreamfrom the service: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).