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

杀马特。学长 韩版系。学妹 提交于 2020-01-05 08:47:07

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/4889439/getting-a-type-specific-response-from-a-wcf-rest-generic-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!