简体   繁体   中英

asp.net core 2.0 model validation not validating data

I am using ASP.NET Core 2.0 default model validation and it seems not working with the ModelState.IsValid always true despite having wrong data in model.

[HttpPost("abc")]
public async Task<IActionResult> Abc([FromBody]AbcViewModel model)
{
    if (!ModelState.IsValid) { return BadRequest(ModelState); }
    ...
}

public class AbcViewModel
{
    [Required(ErrorMessage = "Id is required")]
    [Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
    public int Id { get; set; }

    public bool Status { get; set; }
}

When I post data from Angular app, the values are mapping to model correctly but if Id is "0" or less than 100, both the Required and Range validators aren't working and ModelState.IsValid is always true. What I am missing?

If you're using services.AddMvcCore() , then you need to explicitly set up your application to perform validation with data annotations:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
         .AddDataAnnotations()
         /* etc. */;
}

I used the same model property that you defined in the model and facing the same issue. I made one change in the property and defined the DataMember attribute on the property like:

[Required(ErrorMessage = "Id is required")]
[Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
[DataMember(Name = "Id")]
public int Id { get; set; }

It's working as expected, validating the range values. Try this, hope it will resolve the issue that you are facing.

I also fought with this problem and what helped in my case was adding this in ConfigureServices:

services.AddMvc(opt=> {
    opt.AllowValidatingTopLevelNodes = true;
});

Just be carefull about the outcome - if you want to get automatic BadRequest you have to use [ApiController] attribute . Otherwise you have to check ModelState.IsValid property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM