即使没有 ModelState.IsValid netcore3,模型验证也能正常工作

Model Validation is working even without ModelState.IsValid netcore3

我不会说这是个问题,但我只是好奇。 所以我刚刚开始使用 .net 的 web api,我通常会使用节点或 python 因为它们的构建速度更快,到目前为止非常棒。

无论如何,在我的控制器方法 (post) 中,添加 (ModelState.IsValid) 条件并没有什么不同。

我的意思是代码仍在验证模型,但 post 控制器方法甚至没有做任何事情。希望代码能让它更清晰。

[Route("api/[controller]")]
[ApiController]
public class PeopleController : ControllerBase
{
    private readonly IEntityRepository _entityRepository;

    public PeopleController(IEntityRepository entityRepository)
    {
        _entityRepository = entityRepository;
    }

    [HttpPost]
    public ActionResult<Person> Create(Person person) 
    {
        // if(!ModelState.IsValid){
        //     return new OkObjectResult("wrong shit");
        // } 
        // person.CreatedAt = DateTime.Now;
        // person.Tags = new List<string>();
        // person.Tags.Add($"id+@{person.Id}");
        // person.Tags.Add($"ar+:-{person.Archived}");
        // person.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
        // _entityRepository.Create(person);
        // return person;
        return null;
    }

}


public interface IEntityRepository {

   void Create(Person person);

}

public class EntityRepository : IEntityRepository
{
    private readonly IMongoCollection<Person> _entities;
    public EntityRepository(IConfiguration config)
    {
        var client = new MongoClient(config.GetConnectionString("TestConn"));
        var database = client.GetDatabase("TestDB");
        _entities = database.GetCollection<Person>("Person");
    }

    public void Create(Person person)
    {
        _entities.InsertOne(person);
    }
}


public class Person : IEntity
{
    public string Id { get; set; }

    [Required(ErrorMessage="Name is required")]
    [MinLength(10, ErrorMessage = "Name must be longer than 10 characters")]
    [MaxLength(20, ErrorMessage = "Name must be shorter than 20 characters")]
    public string Name {get;set; }
    [EmailAddress(ErrorMessage = "Enter valid email")]
    [ValidEmail(AllowedDomain = "gmail.com", ErrorMessage = "Invalid email")]
    public string Email {get;set;}
    [Phone(ErrorMessage = "Invalid phone")]
    public string phone {get;set;}
    [BsonElement("archived")]
    public bool Archived { get; set; }

    [BsonElement("tags")]
    public List<string> Tags { get; set; }

    [Required]
    [BsonElement("something")]
    public Something Rotation {get;set;}
}

当我将此添加到 postman

{
    "name": "sssssssssssssssssss",
    "phone": "2323-2323-2323",
    "email": "sd@gmail.com",
    "rotation": { "name": "g"}
}

它仍然有效

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|b6721095-496abaabbf3dbf66.",
    "errors": {
        "Rotation.Name": [
            "The field Name must be a string or array type with a minimum length of '10'."
        ]
    }
}

没关系,刚看到这个https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.0

Web API 控制器不必检查 ModelState.IsValid 是否具有 [ApiController] 属性。在这种情况下,当模型状态无效时,将返回包含问题详细信息的自动 HTTP 400 响应。有关详细信息,请参阅自动 HTTP 400 响应。