WCF 在没有“设置”的属性上窒息。有什么解决办法吗?

作为 service 方法的结果,我传递了一些类,该类具有 get-only 属性:

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

服务方面有个例外:

System.Runtime.Serialization. InvalidDataContractException: 未设置 类型为“ MyNamespace.ErrorBase”的属性“ Message”的方法。

我必须将这个属性设置为只有 getter,我不能允许用户给它赋值。有什么办法吗?还是我漏掉了什么额外的特质?

25661 次浏览

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

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

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

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.

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")].

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.

[DataMember(Name = "PropertyName")]
public string PropertyName
{
get
{
return "";
}
private set
{ }
}

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.

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.