roberto unbaggi
roberto unbaggi

Reputation: 33

Hiding output members with ServiceStack

I'm evaluating ServiceStack as a possible REST service we want to use in our system environment and so far i am quite happy with it. a requirement to the service is hiding fields for particular users or user groups. depending on the key/session a user has not all fields of a data model are returned to the client and they have to be hidden by service stack. therefore after receiving the data object (list) from Linq2SQL i analyse the object with reflection, extract the object members, ignore the members that are supposed to be hidden and add the other members to a dictionary. afterwards i pass the dictionary to ServiceStack which serializes it and sends the data structure to the client.

my questions to this setup are :

Upvotes: 2

Views: 457

Answers (1)

Pauli Price
Pauli Price

Reputation: 4237

The proper way to do it with ServiceStack is to define DTOs for the purpose of your API rather than trying to use existing business objects. If your clients are prepared to parse lists returning a DTO with a dictionary property could work.

One 'ServiceStack' way to do it would be to define a simple, flat, DTO with all possible properties, where each property is Nullable.

Given DTO defined as follows:

public class NullablePartials
{
    public Int32? Test1 { get; set; }
    public String Test2 { get; set; }
    public Double? Test3 { get; set; }
}

The following fragment:

Dictionary<String, String> MyDtoDictionary = new Dictionary<String, String>();
MyDtoDictionary.Add("Test1", "7");
MyDtoDictionary.Add("Test2", "Value2");
NullablePartials result = MyDtoDictionary.ToJson().FromJson<NullablePartials>();

System.Diagnostics.Debug.WriteLine(MyDtoDictionary.ToJson());
System.Diagnostics.Debug.WriteLine(result.ToJson());

produces:

{"Test1":"7","Test2":"Value2"}
{"Test1":7,"Test2":"Value2"}

using ServiceStack.Text as your JSON library in its default setting for serializing nulls.

As for best practices, see https://github.com/ServiceStack/ServiceStack/wiki/Advantages-of-message-based-web-services, where the ServiceStack philosophy is discussed. In particular the recommendation to use:

Code-first POCO's

Since it promotes clean, re-usable code, ServiceStack has always encouraged the use of code-first POCO's for just about everything. i.e. the same POCO can be used:

  • In Request and Response DTO's (on client and server)
  • In JSON, JSV and CSV Text Serializers
  • As the data model in OrmLite, db4o and NHibernate
  • As the entities stored in Redis
  • As blobs stored in Caches and Sessions
  • Dropped and executed in MQ's services
  • Dehydrating complex configurations into

Leveraging different technologies whose functionality is built around POCO's offer un-precedented levels of re-use, reduces friction, promotes consistent, more usable and easier to rationale code-bases.

Upvotes: 3

Related Questions