yesman
yesman

Reputation: 7829

How do you get ServiceStack.ToJson to *sometimes* ignore properties?

I have a ServiceStack DTO:

[Route("/images", "POST")]
public class PostImageCommand
{
    public string Notes { get; set; }
    public byte[] Image { get; set; }
    //other properties removed for brevity
}

I also have a part in my code that logs messages using log4net. I do this by serializing the command. For example, I just do this:

var command = new PostImageCommand(){
    //set properties
};

var commandJson = command.ToJson();
MyLogClass.Log(commandJson);

The problem: The Image byte array can get pretty large. I do not want to serialize this property when logging, or else my log will be filled with large amounts of image data.

I tried putting the [IgnoreDataMember] attribute on the Image byte[] in the DTO. However, that causes the build to fail without Visual Studio saying why. I can put the Attribute on the Image property, but when I try to build I see this:

enter image description here

No reason why the build failed, just these messages. The Output tab only says "The operation was canceled".

My question: What is the easiest way to ignore a DTO property from being serialized in my situation?

Upvotes: 1

Views: 252

Answers (1)

mythz
mythz

Reputation: 143339

This previous answer lists the different ways to ignore properties in ServiceStack.Text. But really if you just want to ignore the property from being logged you can just set the property to null then restore it, map it to a different model with just the types you want serialized using the built-in AutoMapping tools, Use ToObjectDictionary() extension method to serialize your model into a dictionary then remove the items you don't want logged.

The issue you're having with the [IgnoreDataMember] attribute is because you haven't referenced the System.Runtime.Serialization .NET Framework Assembly.

Upvotes: 3

Related Questions