对数据合同实施限制

发布于 2024-12-09 08:26:27 字数 586 浏览 1 评论 0原文

有没有什么方法可以对以数据契约形式作为给定 WCF 服务的参数传递的值实施限制?

例如,请考虑此 Vehicle 类的人为且肯定不可编译的示例:

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

当然,因为没有人希望找到一辆拥有超过 30 个车辆的车辆轮子,我想将 NumberOfWheels 的范围限制为 1 到 30 之间的值。在这种情况下,有没有什么方法可以使用 XSD 限制/方面来限制可接受值的范围?

(请注意,当然,我可以将 NumberOfWheels 的类型从 int 更改为 byte,以进一步限制然而,这并不能解决问题……当然,没有人期望车辆有 255 个车轮。)

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 values 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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你丑哭了我 2024-12-16 08:26:27

下面是一个使用数据注释的示例:

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
}

再次值得注意的是,不能使用此方法将行为发送/强制到客户端。它只会验证对象是否满足所描述的验证。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文