ServiceStack support for conditionally omitting fields from a REST response on a per-call basis

后端 未结 2 928
后悔当初
后悔当初 2021-02-06 13:34

At a minimum, I\'m looking for a way to conditionally exclude certain properties on the resource from being included in the r

2条回答
  •  悲哀的现实
    2021-02-06 14:27

    Usually you can control the serialization of your DTOs by setting the DataMember attributes. With those attributes you can control if the property should have defaults or not. Meaning if you simply do not define the property of the object you want to return, it should not be serialized and therefore will not be shown in the resulting Json.

    ServiceStack internally uses the standard DataContract...Serializer, so this should be supported

    Otherwise you could also make use of dynamic objects and simply compose your object at runtime, serialize it and send it back. Here is a very very basic example:

            var seri = JsonSerializer.Create(new JsonSerializerSettings() { });
    
            using (var textWriter = new StringWriter())
            {
                var writer = new JsonTextWriter(textWriter);
    
                dynamic item = new { Id = id };
    
                seri.Serialize(writer, item);
    
                return textWriter.ToString();
            }
    

提交回复
热议问题