How to configure get-only property for WCF service with Silverlight support

I'm not sure where the error occurs (from silverlight, from wcf, something else ...), but I have a WCF service called from Silverlight. The method returns a class with a property that does not have setter. This causes an error. If I add the setter property to the property, it will not give an error.

The error is the usual impenetrable and useless Silverlight error message, but ...

[Serializable] [DataContract] public SomeClass { DataMember] public string PropertyA { get; set; } public string PropertyB { get { return "Hi There"; } } } 

It gives an error message ...

But change it to:

 [Serializable] [DataContract] public SomeClass { [DataMember] public string PropertyA { get; set; } public string PropertyB { get { return "Hi There"; } set {} } } 

Error.

Includes the regular class ISomeService.svc and SomeService.svc, links updated in Silverlight, calling the asynchronous client, etc. etc.

What is the correct way to configure a property (any attribute other than "DataMember" to allow get-only or private-set property) to pass it through the wire?

+2
source share
2 answers

In your example, the PropertyB is not marked with the DataMember attribute, which means that it will not be displayed in the WSDL and is ignored by the serializer. But if you tag PropertyB with a DataMember, then you must have a setter (private, requested, or public) to serialize it correctly, otherwise you may get an exception. There are two ways I can think of read-only properties serialized over a wire:

 [DataContract] public class SomeClass { public SomeClass() { _propertyB = "Hi there"; } [DataMember(Name="PropertyB")] private readonly string _propertyB; public string PropertyB { get { return _propertyB; } } } 

Or that:

 [DataContract] public class SomeClass { public SomeClass() { PorpertyB = "Hi there"; } [DataMember] public string PropertyB { get; private set; } } 

Note that if you use svcutil.exe , the generated proxy class will have both an open getter and a setter for a property that might not be what you are looking for. In this case, you can use the contract for service and data collection on the client side.

+1
source

Thanks. Private dialing seems sufficient. I donโ€™t like having the installed method there when it is not needed, but I can make a mistake if it is accessed.

 [DataMember] public PropertyB { get { return "Hi there"; } private set { throw new Exception("Empty setter for use by WCF Service."); } } 

Or whatever.

+3
source

Source: https://habr.com/ru/post/1394517/


All Articles