Validation with Modelstate

Asked

Viewed 82 times

0

I have a web application in . NET Framework 4.6.1 with a method similar to the one shown below:

public class MeuControladorController : ApiController
{
    public IHttpActionResult Post([FromBody]AlgumRequest algumRequest)
    {
       try
       {
          if(!ModelState.IsValid)
          {
             return BadRequest(ModelState);
          }

          // Outras cositas mais...

       }
       catch (Exception exception)
       {
          return InternalServerError(exception);
       }
    }
}

The class AlgumRequest is similar to this:

public class AlgumRequest
{
   public IQueDor QueDor { get; set; }
   public byte[] Prop2 { get; set; }
   // ...
}

The estate QueDor is an interface:

public interface IQueDor
{
   string Gritar();
}

Here’s a class that implements it:

public class ChuteCanela : IQueDor, IValidatableObject
{
   [Required]
   public string Texto { get; set; }

   public string Gritar()
   {
      return Texto.ToUpper();
   }

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   {
      if(Texto == "Palavrão")
      {
         yield return new ValidationResult("Calma, acredite que a ideia era acertar a bola. Mantenha a amizade.");
      }
      // ...
   }
}

The problem is that when sending the data to the method Post the property ModelState.IsValid is true even when I send an instance of some class that implements the interface and should be invalidated.

It is possible to solve this problem while using the ModelState?

  • It turns out that the property will have the specified members in the interface and consequently will not contain the validations you created in the specific class.

  • And there would be some way to make the interface also a IValidatableObject? The only way I can think of to solve this would be to create an abstract class and use it instead of the interface. This abstract class could "implement (in an abstract way)" IValidatableObject, so everyone who inherits my abstract class will have to overwrite the validation method.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.