0

I have a simple entity, and one of its property is required:

[DataContract]
 public class Person
 {
     [DataMember]
     public string FirstName { get; set; }
                
     [DataMember (IsRequired=true)]
     public string LastName { get; set; }    
 }

This is the interface of the service:

 [ServiceContract]
 public interface IService1
 {
      [OperationContract]
      Person DoubleLastName(Person person);
 }

and this is the service:

  public class Service1 : IService1
  {      
     public Person DoubleLastName (Person person)
     {
       return new Person { FirstName = person.LastName, LastName = 
                    person.LastName};
       }
  }

And here is the problem: When the client sends an object to this service, without the required property, everything works. Shouldn't I get an exception?

using (Service1Client myProxy = new Service1Client())
{
    Person person1 = new Person {  };   //Here I don't notify the required value.
    Person person = myProxy.DoubleLastName(person1);
}
S Itzik
  • 494
  • 3
  • 12
  • @DingPeng Believe me that if I thought the problem was solved I would have marked it as the answer. Your link doesn't help me in this case. – S Itzik Jan 06 '21 at 05:35
  • @Ding In the link you provided, you can see it was introduced in .NET Framework 3.0. didn't see the word "Only". – S Itzik Jan 08 '21 at 08:32
  • I think this may be due to some optimizations made after .net 3.0 that did not raise this exception. If we serialize and deserialize the Person object ourselves, an exception will still be thrown. – Ding Peng Jan 19 '21 at 06:06

1 Answers1

0

This is because DataMemberAttribute.IsRequired applies to .NET Framework 3.0:

enter image description here

For more information about it, you can refer to this link.

I tried to use .NET Framework3.0 for testing and got an exception:

enter image description here

Ding Peng
  • 3,702
  • 1
  • 5
  • 8
  • So Microsoft broke the code? Sound strange. I understand it was introduced at dotNetFramework 3.0, BUT shouldn't it work at later versions? and if this is the case, what is the attribute which replaced IsRequired attribute? – S Itzik Jan 04 '21 at 08:36
  • For the official Microsoft explanation, you can refer to this link: https://learn.microsoft.com/en-us/dotnet/framework/wcf/best-practices-data-contract-versioning – Ding Peng Jan 04 '21 at 08:41