Eugene Zakharov
Eugene Zakharov

Reputation: 157

Data annotations attributes not working in asp net core

ASP Net core 2.2 application, data annotations attributes [Required] is not working at all. According docs https://learn.microsoft.com/en-ca/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.1#remarks . A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters. However, it's not the case in my application.

        [HttpPost]
        public IActionResult TranslateHtml(
            [FromQuery] [Required] int value,
            [FromForm] [Required(AllowEmptyStrings = false)]
            string source)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            return Ok();
        }

When I'm sending request via Postman and do not specify query string value and/or form data source ModelState.IsValid is true. I'm expecting false.

Upvotes: 5

Views: 5960

Answers (1)

Eugene Zakharov
Eugene Zakharov

Reputation: 157

I figured out the source of a problem. I was included .AddMvcCore, and by default it's not including DataAnnotations at all.

services.AddMvcCore()
        .AddDataAnnotations()
        .AddCors()
        .AddJsonFormatters()

I've added .AddDataAnnotations in Startup.cs and it works like a charm.

Upvotes: 9

Related Questions