You need to enable JavaScript to run this app. C#如何在StringLength等数据注解中调用类方法获取动态错误消息
优惠活动
大模型
产品
解决方案
定价
更多

C#如何在StringLength等数据注解中调用类方法获取动态错误消息

问题核心原因

.NET 特性(Attribute)的所有参数必须为编译时常量,你直接在ErrorMessage参数中调用自定义方法的写法不符合语法要求,方法返回值是运行时计算的,编译阶段无法获取,因此必然不生效。
另外你提供的Helpers类存在语法错误:普通方法不能包含get/set访问器,这是C#属性的专属语法,该类本身无法编译通过。

可行解决方案

方案1:自定义继承自StringLengthAttribute的验证特性(最符合通用化需求)

直接封装逻辑到自定义特性中,不用每次重复写消息模板:

// 自定义特性类
public class CustomStringLengthAttribute : StringLengthAttribute
{
    /// <param name="maximumLength">字符串最大长度</param>
    /// <param name="messageTemplate">消息模板,{0}会自动替换为最大长度值</param>
    public CustomStringLengthAttribute(int maximumLength, string messageTemplate = "Up to {0} characters can be entered.") 
        : base(maximumLength)
    {
        ErrorMessage = string.Format(messageTemplate, maximumLength);
    }
}

在Model中使用:

[Required(AllowEmptyStrings = false)]
[CustomStringLength(19)] // 仅传长度即可,消息自动生成
public long UserId { get; set; }

[Required(AllowEmptyStrings = false)]
[CustomStringLength(50)]
public string Email { get; set; }

[Required(AllowEmptyStrings = false)]
[CustomStringLength(25, "最多允许输入{0}个字符")] // 也可自定义消息模板
public string Business { get; set; }

方案2:使用常量类存储固定提示(适合消息固定不变的场景)

如果不需要动态拼接长度,可把提示文本定义为公共常量,特性参数支持常量赋值:

public static class ValidationMessageConstants
{
    public const string MaxLength50 = "Up to 50 characters can be entered.";
    public const string MaxLength25 = "Up to 25 characters can be entered.";
}

使用示例:

[Required(AllowEmptyStrings = false)]
[StringLength(50, ErrorMessage = ValidationMessageConstants.MaxLength50)]
public string Username { get; set; }

内容的提问来源于stack exchange,提问作者johnvayne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 04:15:00