Mr.Cappuccino
Mr.Cappuccino

Reputation: 126

Model Validation is working even without ModelState.IsValid netcore3

I wouldn't say this is a problem but something I'm just curious about. So I've just started using .net for web api's, I'd normally use node or python cause they're faster to build, pretty awesome so far.

Anyway in my controller method (post), Adding a (ModelState.IsValid) condition doesnt make a difference.

I mean the code still validates the model, but the post controller method isnt even doing anything. Hopefully the code makes it clearer.

[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;}
}

When i add this to postman

{
    "name": "sssssssssssssssssss",
    "phone": "2323-2323-2323",
    "email": "[email protected]",
    "rotation": { "name": "g"}
}

It still validates

{
    "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'."
        ]
    }
}

Upvotes: 0

Views: 1863

Answers (1)

Mr.Cappuccino
Mr.Cappuccino

Reputation: 126

Nevermind, just saw this https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.0

Web API controllers don't have to check ModelState.IsValid if they have the [ApiController] attribute. In that case, an automatic HTTP 400 response containing issue details is returned when model state is invalid. For more information, see Automatic HTTP 400 responses.

Upvotes: 6

Related Questions