StringLengthAttribute 似乎不起作用

发布于 2024-10-14 07:42:51 字数 701 浏览 6 评论 0原文

这是我的带有数据注释的测试类:

class Test
{
  [Required, StringLength(10)]
  public string MyProperty { get; set; }
}

这是我的控制台测试程序:

class Program
{
  static void Main(string[] args)
  {
    var test = new Test {
      MyProperty = "this is way more than 10 characters and should fail."
    };

    var context = new ValidationContext(test, null, null);

    // No exception here! (why not?)
    Validator.ValidateObject(test, context);

    test.MyProperty = null;

    // Exception here, as expected
    Validator.ValidateObject(test, context);
  }
}

由于某种原因,当字符串长度太长时,我没有收到验证异常。当我将属性设置为 null 并重新验证时,我确实遇到了验证异常(如预期)。有什么想法为什么我的字符串长度注释没有被强制执行吗?

Here is my Test class with data annotations:

class Test
{
  [Required, StringLength(10)]
  public string MyProperty { get; set; }
}

Here is my console test program:

class Program
{
  static void Main(string[] args)
  {
    var test = new Test {
      MyProperty = "this is way more than 10 characters and should fail."
    };

    var context = new ValidationContext(test, null, null);

    // No exception here! (why not?)
    Validator.ValidateObject(test, context);

    test.MyProperty = null;

    // Exception here, as expected
    Validator.ValidateObject(test, context);
  }
}

For some reason, I do not get a validation exception when the string length is too long. I do get a validation exception (as expected) when I set the property to null and re-validate. Any ideas why my string length annotation is not being enforced?

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

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

发布评论

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

评论(3

请恋爱 2024-10-21 07:42:51

虽然有点不直观,但是改变一下

Validator.ValidateObject(test, context);

就能

Validator.ValidateObject(test, context, true);

解决问题。第三个参数是bool validateAllProperties。我不确定为什么以前强制执行 [Required] 属性,而未强制执行 [StringLength] 属性,但至少现在一切正常。

It's a bit non-intuitive, but changing

Validator.ValidateObject(test, context);

to

Validator.ValidateObject(test, context, true);

solves the problem. The third argument is bool validateAllProperties. I'm not sure why the [Required] attribute was previously being enforced while the [StringLength] wasn't, but at least it all works now.

万劫不复 2024-10-21 07:42:51

感谢您发布此内容。我在 Microsoft Connect 上发布了针对此问题的错误。我认为他们错误地跳过了 System.String 属性,因为它不是值类型,因为他们在没有“validateAllProperties”参数的情况下不会进行深度/递归验证。

如果您有兴趣,这是错误链接:
https://connect.microsoft.com/VisualStudio/feedback/details/672247/system-componentmodel-dataannotations-validator-does-not-validate-stringlengthattribute-unless-validateallproperties-specified

Thanks for posting this. I posted a bug on Microsoft Connect for this issue. I assume that they are incorrectly skipping a System.String property as it is not a value type because they do not do a deep/recursive validation without the "validateAllProperties" parameter.

Here's the bug link if you're interested:
https://connect.microsoft.com/VisualStudio/feedback/details/672247/system-componentmodel-dataannotations-validator-does-not-validate-stringlengthattribute-unless-validateallproperties-specified

缺⑴份安定 2024-10-21 07:42:51

它在 WebAPI 上下文中对我不起作用。然而,经过很少的进一步研究,我找到了解决方案。

使用 ModelState.IsValid 以及数据注释来解决此问题,如下所示:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

这将为调用者创建 400(错误请求)响应,如下所示:

{"Message":"The request is invalid.","ModelState":{"reqs.ImportRows[0].SMSConsent":["The field SMSConsent must be a string with a maximum length of 1."]}}

最好的部分是,它为调用者提供列表的确切行号,如果请求是一个列表对象。这对于您的 3rd 方客户使用您的 api 来调试、分析和修复问题非常有帮助。

It did not work for me in the WebAPI context. However, with little further research I found a solution.

Use ModelState.IsValid along with your data annotations to resolve this problem as follows:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

This will create a 400 (bad request) response to the caller as follows:

{"Message":"The request is invalid.","ModelState":{"reqs.ImportRows[0].SMSConsent":["The field SMSConsent must be a string with a maximum length of 1."]}}

The best part is, it provides the caller with the exact row number of the list if the request is a list object. This is very helpful to your 3rd party clients using your api to debug, analyze and fix the issue.

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