Search code examples
c#visual-studio-2010wcfrestscriptignore

ScriptIgnore not working on WCF REST service application


I started a Visual Studio WCF Rest Service Application project where I want to have a service that returns a Json formatted message with a serialized object and I want SOME fields of the object not being serialized. I must say that my knowledge of WCF is very very basic and that I used the Rest Service Application project from Visual Studio because it's a simple way to implement what I need fast.

Let's say this is the object I have:

public class BaseMessage
{
    public string errorCode { get; set; }
    public string errorMessage { get; set; }
}

And this is my code

    [WebGet(UriTemplate = "/v1/test", 
    ResponseFormat = WebMessageFormat.Json),OperationContract]

    public BaseMessage Test()
    {
        return (new BaseMessage { errorCode = "000", errorMessage = "test" });
    }

I've read everywhere that what I need to do is to assign the [ScriptIgnore] attribute to the properties I don't want to have serialized. But if I do, it doesn't work. I get them serialized anyway.

The only way I have achieved what I want to do is declaring the object I want to return in this way:

[Serializable]
public class BaseMessage
{
    public string errorCode;
    [NonSerialized]
    public string errorMessage;
}

In this way I get the class serialized as I want. But it bugs me a lot as I might not be doing this thing right. Am I doing this right?


Solution

  • I think you should be using [DataContract] attribute for your data objects and [DataMember] for your object members

    like here http://msdn.microsoft.com/en-us/library/ms733127.aspx

    When you want to ignore an item; you mark it as [IgnoreDataMember] attribute