5

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using the services.AddControllers() method instead, but my [Required(AllowEmptyStrings = false)] annotation is not working. I also tried calling AddMvcCore().AddDataAnnotations() as well just in case, but it made no difference. Any clue please?
@killswitch which .net version and application are you using? can you paste a snippet somewhere of your startup class?
Never mind, it was a silly mistake from my end. I'm using .Net 6 and the "AddControllers" method internally calls "AddDataAnnotations", so it works automatically. Thanks for your interest!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.