开发者

Object serialization: selecting individual properties

A dumb question: Let's say I have an object that i store in viewstate. I have it marked as Serializable. I also reuse the same object in my WCF service. But the web service serializes and exposes some internal properties that are not necessary/safe to display to a service client. Is there a way to allow field/property serialization for ViewState but not Web Service? [NonSerialized] hides properties from both. I know I can implement a POCO for web service use, but I wanted to keep method/object signatures unchanged as far as the class names. Just wonder if the开发者_如何学Cre's a way. If not, i'm gonna have to either live without those fields in ViewState or create POCOs and let customers worry about reimplementing their clients.

Thanks


Yes, when creating a DataContract for a web service, you mark the members you want to be included in the service requests and replies with the [DataMember] attribute.

[DataContract]
[Serializable]
public class MyData
{
    private int id_value;

    // Apply the DataMemberAttribute to the property.
    [DataMember]
    public int ID
    {

        get { return id_value; }
        set { id_value = value; }
    }

    public int DontExposeMeToWcf { get; set; }
}

Edit: In .NET 4.0 you can also use the [IgnoreDataMember] Attribute to exclude a member from serialization. From Using Data Contracts:

By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized. You can opt out members from serialization by using the IgnoreDataMemberAttribute.

The IgnoreDataMemberAttribute attribute is only honored when used with unmarked types. This includes types that are not marked with one of the DataContractAttribute, SerializableAttribute, CollectionDataContractAttribute, or EnumMemberAttribute attributes, or marked as serializable by any other means (such as IXmlSerializable).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜