开发者

Enforcing Restritions On DataContracts

Is there any way one can enforce restrictions on values passed in the form of data contracts as parameters to a given WCF Service?

For instance, please consider the contrived and certainly non-compilable 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, nobody expects to find a vehicle with more than, say, 30 wheels, I would like to limit the range of the NumberOfWheels to a value between 1 and 30. Is there any way one can use XSD restrictions/facets to limit the range of acceptable va开发者_如何学Golues in this case?

(Please note that I could, of course, change the type of the NumberOfWheels from int to, say, byte to further limit the range of possible values. However, that wouldn't solve the problem... Of course, no one expects a vehicle to have 255 wheels.)


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 behavior cannot be sent/forced to the client using this method. It will only validate that the object fulfills as described validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜