I'm attempting to pass a complex object as a parameter to a WCF service via the WCF test client, but getting nulls on the service side. The object is called mailParameters and it contains some strings and custom objects named "eMailAddress" (I simplified the code for clarity). The classes are decorated with [DataContract] and methods with [DataMember] and, when the parameters are set, only the Subject and Body strings are sent to the WCF service while the other objects remain null (the "eMailAddress").
Here's the Interface:
[ServiceContract]
public interface ISendMailService
{
[OperationContract]
void DeliverEmail(mailParameters mailParams);
}
[DataContract]
public class mailParameters
{
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Body { get; set; }
[DataMember]
public eMailAddress Sender { get; set; }
[DataMember]
public eMailAddress MailFrom { get; set; }
}
[DataContract]
public class eMailAddress
{
private string _Address;
[DataMember]
public string Address
{
get
{
return _Address;
}
set
{
_Address = Address;
}
}
private string _Name;
[DataMember]
public string Name
{
get
{
return _Name;
}
set
{
_Name = Name;
}
}
}
And the implementation (no actual working code, but stepping via debug to see if all the mailParams came through after invocation).
public class SendMailService : ISendMailService
{
public void DeliverEmail(mailParameters mailParams)
{
//throw new NotImplementedException();
}
}
When I check the values of mailParams passed to the DeliverEmail method, the Subject and Body are correct, but the mailParams.MailFrom.Address and the mailParams.MailFrom.Name are both null (the same for mailParams.Sender...)
I've also tried putting the eMailAddress class inside the mailParameters class and get the same results.
I can't find simple examples (yes, I'm a noob to WCF) on how to pass complex objects as parameters to a WCF service, only simple objects (which works fine). Not sure how to proceed . Any ideas?
The cause for this is, that you've put the [DataMember]
-attribute in the wrong place. In your mailParameters
-class you're using auto-properties whereas you're not using these in your eMailAddress
-class.
WCF requires that field or property being decorated with the [DataMember]
-attribute, which will actually hold the information. So in your case, there are two options:
Option 1:
[DataContract]
public class eMailAddress
{
[DataMember]
public string Address { get; set; }
[DataMember]
public string Name { get; set; }
}
Option 2:
[DataContract]
public class eMailAddress
{
[DataMember]
private string _Address;
public string Address
{
get
{
return _Address;
}
set
{
_Address = Address;
}
}
...
}