Search code examples
c#asp.netninjectdata-annotationsrequired

C# RequiredAttribute messages on RESTful service appear double


I'm having a RESTful service done with C# ASP.NET. On my models, I'm using the DataAnnotations' RequiredAttribute (from System.ComponentModel.DataAnnotation). When I'm sending an input model with missing properties (via Swagger or Postman), I get double $"{property} is required" messages, although I only have one [Required] attribute on each property. I thought maybe it comes from inheritance in my models (I sometimes also have three-level hierarchies and no triple messages, so I think this is not the problem) or from registering the validations double somehow (but where are they registered?). For example, this is one parent:

public class CertificatePayload : AchievementBase
{
    public string ExternalLink { get; set; }
}

and this one child class:

public class AchievementBase
{
    [Required]
    public string GrantedTo { get; set; }
    [Required]
    public string GrantedBy { get; set; }
 }

Any ideas about what I could check or what could be the problem?


Solution

  • Since there came no answer... A colleague of mine solved the problem with a trick: deleting the required attributes and adding the IValidatable interface to the object with a validate method showed that the validate method was called twice. Stacktrace was the same both times. The right search words found the solution in the end: StackOverflow-ASP.NET WEB API 2 - ModelBinding Firing twice per request

    I had to rebind the ModelValidatorProvider. I applied it to where I had bound my Entities.