4

Currently we are setting up a new project and like to use the new records introduced in C# 9. We encounter a problem with DataAnnotations inside the record (constructor) not being triggered during the unittest.

Now the DataAnnotation is triggered when calling the Controller, but when i try to simulate this in a unittest (see code below) it will never return any errors.

        //Unit Testing ASP.NET DataAnnotations validation
        //http://stackoverflow.com/questions/2167811/unit-testing-asp-net-dataannotations-validation
        protected static IList<ValidationResult> ValidateModel(object model)
        {
            var validationResults = new List<ValidationResult>();
            var ctx = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, ctx, validationResults, true);
            return validationResults;
        }

Currently we created a workaround:

    public record FooRecord(string BarProperty)
    {
        [Required]
        public string BarProperty { get; init; } = BarProperty;

    }

But I'm hoping if someone knows why this happens and maybe know how to solve this using the shorthand syntax:

    public record FooRecord([Required] BarProperty){ }
Marco
  • 41
  • 3

2 Answers2

5

It will work as expected if you define your record as:

public record FooRecord([property: Required] BarProperty){ }
zeroid
  • 701
  • 7
  • 19
  • I have `[StringLength]` attribute. I expect it should work same way. `property: ` gives the following error: `Record type 'AuthCodeRequest' has validation metadata defined on property 'AuthCode' that will be ignored. 'AuthCode' is a parameter in the record primary constructor and validation metadata must be associated with the constructor parameter` `param: ` and just `[StringLength]` works – SerjG Mar 04 '22 at 02:14
  • Also worked for MongoDb driver such as [property: Bson] – Reza Taba Dec 10 '22 at 23:14
  • same error as SerjG – Siarhei Kavaleuski Jul 13 '23 at 15:58
0

Behavior of ASP.NET Core request parameters

You can't apply validation attributes [property: ... ] to your request parameters that undergoes binding & validation, see this question.

You will receive InvalidOperationException(...) like @SerjG describes in his comment.

It happend to me too and that is the reason why end up in this SO thread.

For details, see this issue.

Solution

  • Replace remove your validation attributes.
  • Use Fluent Validation instead.
KUTlime
  • 5,889
  • 1
  • 18
  • 29