C# 如何在 REST API 中验证 null 可选数组参数?

发布于 2025-01-15 10:55:53 字数 474 浏览 2 评论 0原文

想象一下,我有一个接受可选 MyParam 字符串数组 属性的端点。 如何用最基本的方法检查它是否为空或为空 - 数据注释将是最好的。

https://stackoverflow.com/questions/ask?MyParam=

  • [Required] 不是一个选项,因为参数必须是可选的
  • [StringLength] 与MinimumLength 不起作用
  • [MinLength] 根本不起作用
  • [RegularExpression(@"\S+")] 根本不起作用

更新: 我想在字符串数组上执行此操作,而不仅仅是字符串,抱歉造成混乱。希望这有助于证明为什么上述数据注释不起作用。

Imagine that I have an endpoint that accepts optional MyParam string array attribute.
How to check it if it's null or empty with most basic way - Data Annotations would be the best.

https://stackoverflow.com/questions/ask?MyParam=

  • [Required] is not an option as parameter has to be optional
  • [StringLength] with MinimumLength doesn't work
  • [MinLength] doesn't work at all
  • [RegularExpression(@"\S+")] doesn't work at all

Update:
I want to do it on string array not just string, sorry about confusion. Hope this help to justify why above DataAnnotations don't work.

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

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

发布评论

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

评论(1

泛滥成性 2025-01-22 10:55:53

我认为您在这里看到的是自定义模型验证属性。

例如:

public class MyParamValidationAttribute : ValidationAttribute
{
    public MyParamAttribute(string param)
    {
        Param = param;
    }

    public string Param { get; }

    public string GetErrorMessage() =>
        $"Invalid param value {param}.";

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var myParam = (string)value;

        if (string.IsNullOrEmpty(myParam))
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }
}

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#custom-attributes-1

I think what you're looking at here is a custom model validation attribute.

For example:

public class MyParamValidationAttribute : ValidationAttribute
{
    public MyParamAttribute(string param)
    {
        Param = param;
    }

    public string Param { get; }

    public string GetErrorMessage() =>
        
quot;Invalid param value {param}.";

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var myParam = (string)value;

        if (string.IsNullOrEmpty(myParam))
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }
}

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#custom-attributes-1

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