WCF chokes on properties with no "set ". Any workaround?
Asked Answered
H

9

103

I have some class that I'm passing as a result of a service method, and that class has a get-only property:

[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message { get { return ""; } }
}

I'm getting an exception on service side:

System.Runtime.Serialization.InvalidDataContractException: No set method for property 'Message' in type 'MyNamespace.ErrorBase'.

I have to have this property as only getter, I can't allow users to assign it a value. Any workaround I could use? Or am I missing some additional attribute?

Howitzer answered 24/2, 2010 at 2:29 Comment(1)
Don't mark a property that cannot be deserialized with [DataMember]. Adding the attribute will simply cause DataContractSerializer to throw an exception instead of checking if the property can be serialized or deserialized.Geilich
D
112

Give Message a public getter but protected setter, so that only subclasses (and the DataContractSerializer, because it cheats :) may modify the value.

Drisko answered 24/2, 2010 at 2:34 Comment(5)
Thanks, glad it was useful! This actually is just one of several uses for this trick. Since getters and setters are technically functions, you can also use this same technique to provide custom serialization of primitive types (perhaps a custom time format in XML) without needing to wield the intimidating IDataContractSurrogate.Drisko
You could even make it private. The Serializer doesn't mind whether it's private, public, protected, internal or protected internal.Distressed
and make the setter throw new NotSupportedException()Restitution
Dont' forget the [DataMember] attribute :)Maladjustment
Having a private set; works if you use [DataContract] and [DataMember]. If you omit them, you need public set;.Evesham
A
13

Even if you dont need to update the value, the setter is used by the WCFSerializer to deserialize the object (and re-set the value).

This SO is what you are after: WCF DataContracts

Argon answered 24/2, 2010 at 2:31 Comment(3)
So the only way for me to overcome the problem is to make it a method instead of property? Again, I can't allow "set" on this propertyHowitzer
You could make it a method (eg GetMessage() { return ""; }) alternatively, I am pretty sure you could tell the WCF Serializer to ignore it. I'll see what I can find and let you know.,Argon
This stackoverflow question hits the nail on the head: https://mcmap.net/q/211936/-wcf-datacontractsArgon
H
12
[DataMember(Name = "PropertyName")]
public string PropertyName
{
    get
    {
        return "";
    }
    private set
    { }
}
Holinshed answered 6/8, 2012 at 11:21 Comment(0)
R
7

If you only have a getter, why do you need to serialize the property at all. It seems like you could remove the DataMember attribute for the read-only property, and the serializer would just ignore the property.

Radionuclide answered 23/9, 2016 at 21:18 Comment(1)
It does indeed not make sense to serialize a derived property (e.g., an URL property that is computed from an ID property) to a persistent storage (e.g., a database) - upvote for that - but it does make sense to serialize it to a representation (e.g., JSON or XML) that is returned by an API request.Persuasion
N
5

Couldn't you just have a "do-nothing" setter??

[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message 
  {
      get { return ""; } 
      set { }
  }
}

Or does the DataContract serializer barf at that, too??

Nankeen answered 24/2, 2010 at 6:5 Comment(1)
It doesn't barf, I just didn't want to let the developers using the client API think that they can assign stuff to the property.Howitzer
B
2

Properties with DataMember attribute always requires set. You should re write simmilar object on the client application since DataContract members can always be assigned values.

Bevon answered 24/2, 2010 at 6:16 Comment(0)
A
2

I had this problem with ASP.NET MVC and me wanting to use DataContractSerializer in order to be able to control the names on the items in the JSON output. Eventually I switched serializer to JSON.NET, which supports properties without setters (which DataContractSerializer doesn't) and property name control (which the built-in JSON serializer in ASP.NET MVC doesn't) via [JsonProperty(PropertyName = "myName")].

Agonic answered 13/9, 2011 at 9:58 Comment(0)
L
2

If it's a viable option, then instead of having ErrorBase as the base class, define it as follows:

    public interface IError
    {
        string Message
        {
            [OperationContract]
            get;

            // leave unattributed
            set;
        }
    }

Now, even though a setter exists, it's inaccessible to the client via WCF channel, so it's as if it were private.

Liam answered 25/5, 2012 at 22:32 Comment(0)
R
1

If your serializer is of type DataContractJsonSerializer (or any DataContractSerializer) you can also use DataContractSerializerSettings in the constructor, with the SerializeReadOnlyTypes property set to true.

Reeves answered 28/5, 2020 at 13:39 Comment(1)
Thanks! I did not know that option existed.Geilich

© 2022 - 2024 — McMap. All rights reserved.