从服务器端设置值时的验证属性.Net Core

问题描述 投票:0回答:1

当我从服务器端将值设置为 prop 具有验证属性“MaxLength”时,应用程序不会抛出异常。

public class Student
    {
        public Guid Id { get; set; }

        [MaxLength(40,ErrorMessage ="too long")]
        public string Name { get; set; }
    }


  [HttpPost("AddStudent")]
        public IActionResult AddStudent()
        {
            string studentName = System.IO.File.ReadAllText(@"C:\StudentName.txt");

            Student student = new Student()
            {
                Id = Guid.NewGuid(),
                Name = studentName, // Name larger than 40 char
            };            

            //Add student to DB

            return Ok();
        }

我希望在设置无效值时直接抛出异常

c# .net-core data-annotations
1个回答
0
投票

MaxLength
是MVC中的数据注释属性。当您手动创建 Student 对象时,除非显式调用模型验证器,否则它将不起作用。顺便说一句,如果您从请求参数/查询字符串绑定学生班级属性值,它会自动执行。

© www.soinside.com 2019 - 2024. All rights reserved.