09 October, 2013

No set method for property in WCF service

Problem:

I have some class that I'm passing as a result of a service method, and that class has a get-only property:
 

public string PropertyName
{
    get
    {
        return "Some Value";
    }    
}

 I'm getting an exception on service side "No set method for property"

Solution:

Remember that WCF needs to create an instance of the object from its serialized representation (often XML) and if the property has no setter it cannot assign a value. Objects are not transferred between the client and the server but only serialized representations, so the object needs to be reconstructed at each end.

Make setter property private. So, client can never see the set method on your property acting much like a read only property. 

public string PropertyName
{
    get
    {
        return "Some Value";
    }
    private set
    { }
}

No comments:

Post a Comment