Why some of my Data Annotations in my dto class are not working when I validate the Model in my WebApi?

asp.net-mvc asp.net-web-api c# data-annotations entity-framework-core

Question

I have Dto class with data annotations on my properties, but one of them is getting ignored when ModelValidation is performed:

Dto Class:

public class TestClassDto {
 [Required()] //This one is getting ignored!
 public virtual System.Guid Id { get; set; }

 [StringLength(32)]
 [Required()]
 public virtual string Type { get; set; }

 [Required()]
 public virtual string Description { get; set; }
}

Original Class:

public class TestClass {
 public virtual System.Guid Id { get; set; }

 public virtual string Type { get; set; }

 public virtual string Description { get; set; }
}

My Post Controller:

[HttpPost]
public async Task<IActionResult> PostTestClass([FromBody] TestClassDto testClassDto) {
  //if (!ModelState.IsValid) return BadRequest(ModelState); Explicit ModelState Validation is not necessary because ControllerBase makes Validation automatically

  TestClass testClass = _mapper.Map<TestClassDto, TestClass>(testClassDto);
  _uow.TestClassRepository.Add(testClass);

  try {
    await _uow.CompleteAsync();
  } catch (DbUpdateException ex) {
    return StatusCode(500, ex.ToString());
  }

  TestClassDto result = _mapper.Map<TestClass, TestClassDto>(testClass);

  return CreatedAtAction("GetTestClass", new { id = result.Id }, "Great");
}

Why is this happening? Any ideas would be helpful! Thanks in advance :)

1
0
8/1/2019 12:42:57 PM

Popular Answer

System.Guid is a value type and it has a default value (actually an instance of) Guid.Empty, so it's never null. Because of that, the [Required] attribute will always pass the validation.

One of the solutions and probably the easiest one is to make the Guid nullable, like so:

[Required] public virtual System.Guid? Id { get; set; }

or the longer version:

[Required] public virtual Nullable<System.Guid> Id { get; set; }

1
8/1/2019 7:59:03 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow