WCF chokes on properties with no “set ”. Any workaround?

后端 未结 9 746
别跟我提以往
别跟我提以往 2020-12-02 11:34

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
{
  [DataM         


        
相关标签:
9条回答
  • 2020-12-02 12:11

    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

    0 讨论(0)
  • 2020-12-02 12:12

    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.

    0 讨论(0)
  • 2020-12-02 12:13

    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.

    0 讨论(0)
  • 2020-12-02 12:17

    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??

    0 讨论(0)
  • 2020-12-02 12:17

    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.

    0 讨论(0)
  • 2020-12-02 12:23

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

    0 讨论(0)
提交回复
热议问题