Question

I am defining a web service which calls a service library. The service library has an object called customer with a customer ID defined the following way:

public class Customer
{
    private int _customerID;
    public int CustomerID
    {
        get { return _customerID; }
    }
}

When I try to pass a customer object back through my web service, it seems that the WSDL generated doesn't include the property CustomerID, unless I define a setter. It seems like requiring a setter is undesireable in certain circumstances. Am I missing something, or does generating a WSDL require a property to have a getter/setter in order to be exposed to the client?

Was it helpful?

Solution

The other answers are correct, but don't mention that this is a restriction of the XML Serializer, which is used by ASMX web services.

ASMX web services are now considered by Microsoft to be "legacy technology", and should not be used for new service development. Their replacement, WCF, does not have this restriction.

OTHER TIPS

See if this helps: http://support.microsoft.com/kb/313584

It appears this is a requirement, what you could do is throw an exception should a client try to set this property.

From the link I posted

To work around this problem, add a SET procedure for the property. You can either leave the procedure empty, so that that the procedure has no effect, or raise a custom exception to inform clients that the property is read-only, as follows:

Public Property Id() As Integer
    Get
        Return nID
    End Get
    Set(ByVal Value As Integer)
        Throw New Exception("Cannot set read-only property 'Id'")
    End Set
End Property

Yours could become:

public class Customer
{
    private int _customerID;
    public int CustomerID
    {
        get { return _customerID; }
        set { throw new exception("Cannot set value!"); }
    }

}

The setter is required so .Net can set the property after transfer (during deserialization). You can solve this by implementing your own object or possibly by setting it as internal: internal set { }

This is actually more of a security consideration so it should be supported, but default .Net behavior is 1-1 mapping of properties in WSDL. If internal setter doesn't work (I expect it won't) and you don't want to bother with custom ser/deser then just add a throw new SecurityException() to the setter.

You can bypass the required setter by implementing your own custom serialization, but I'm unsure how the WSDL will look. I haven't tried it, but I suspect a combination of custom serialization and internal setter will solve the problem.

EDIT: As @John Saunders points out the setter limitation may not be there in WCF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top