代码之家  ›  专栏  ›  技术社区  ›  JSON

如何在asp中重写模型状态错误消息。net Core 2.1?

  •  1
  • JSON  · 技术社区  · 7 年前

    我似乎无法覆盖来自的模型状态验证的错误消息 int 或可为空的 int? . 在Asp的早期版本中。Net Core我以前收到的输入无效,现在我收到了这个不友好的错误,

    {“streetNo”:[“无法将字符串转换为整数:abc。路径‘cityId’, 第24行,位置23。"]}

    所以我尝试使用自定义验证属性来解决这个问题,

    我创建了这个类,

     public class IsInt : ValidationAttribute {
            public IsInt () : base () { }
    
            public override bool IsValid (object value) {
                Console.WriteLine (value);
                if (value.IsNullObject ()) {
                    return true;
                } else {
                    if (value.GetType () == typeof (int?)) {
                        return true;
    
                    } else {
                        return false;
                    }
                }
            }
            protected override ValidationResult IsValid (
                Object value,
                ValidationContext validationContext) {
    
                var message = "Only number is allowed";
                return new ValidationResult (message);
            }
        }
    

    我是这样实施的,

    [IsInt]
    public int? StreetNo { get; set; }
    

    validation属性似乎没有按预期工作,如果我输入一个字符串,即“abc”,我仍然收到提到的模型错误消息,它只在字符串中有数字时工作,即“83444”

    我错过了什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andy Raddatz    7 年前

    我有一个类似的问题,我想重写消息,这样它们就不会总是直接向用户显示“字段MyLongDescriptivePropertyName必须是一个数字”。其实有一种简单的方法 Startup.cs :

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(o =>
            {
                o.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(val => "Must be a number.");
            });
        }
    

    The class description here 没有真正解释或举例说明。我发现 this post 很接近,但他们添加了 Set...Accessor() 方法,所以这就是您目前的分配方式。

    推荐文章