Forced restrictions on DataContracts

Is there any way to apply the restrictions on the values ​​transferred in the form of data contracts as parameters for this WCF service?

For example, consider a far-fetched and, of course, non-compiled example of this Vehicle class:

 [DataContract] public class Vehicle { [DataMember] [Restriction(MinValue = 1, MaxValue = 30)] // Certainly not allowed... or is it? public int NumberOfWheels { get; set; } } 

Since, of course, no one expects to find a car with more than, say, 30 wheels, I would like to limit the range of NumberOfWheels to 1 to 30. Is there a way that you can use XSD constraints / faces to limit the range of acceptable values ​​in this case ?

(Note that, of course, I could change the NumberOfWheels type from int to, say, byte , to further limit the range of possible values. However, this would not solve the problem ... Of course, no one expects the car to have 255 wheels.)

+4
source share
1 answer

Here is an example using dataannotations:

 using System.ComponentModel.DataAnnotations; [DataContract] public class Test { [DataMember] [Range(1, 30)] public int MyProperty { get; set; } } public void DoWork(Test t) { // this will throw validation exceptions, overloads are available to trap and handle Validator.ValidateObject(t, new ValidationContext(t), true); //do stuff here } 

Again, it should be noted that the behavior cannot be sent / forced to the client using this method. It will only verify that the object performs as described verification.

+3
source

All Articles