Bheema Vidyuth

Bheema Vidyuth

  • 1.5k
  • 503
  • 142.1k

Data Annotation error message is not displaying in postman response

Mar 29 2021 7:45 AM
Hi all,
 
i have web api 3.0 solution and i dont have any UI for that.All my response i have cheking in postman only .
For input validation i have used data annotation but i couldnt see the error message in post man.please help me what mistake i have done.
 
currently i am getting the error message like:
 
{
"studentid": [
"Error converting value {null} to type 'System.Int32'. Path 'studentid', line 2, position 26."
]
}
 
but i want to display the error message like:
  1. [Required (ErrorMessage = "student Id is required.This cannot be null or blank")]  
  2. public int StudentId { getset; }  
What i have done so far:
 
1. my model
  1. public class Employee  
  2. {  
  3. [Required (ErrorMessage = "student Id is required.This cannot be null or blank")]  
  4. public int StudentId { getset; }  
  5. [Required (ErrorMessage = "Student name is required.This cannot be null or blank")]  
  6. [StringLength(100, MinimumLength = 2)]  
  7. public string FirstName { getset; }  
  8. [Required]  
  9. public string LastName { getset; }  
  10. [Required (ErrorMessage = "Student age is required.This cannot be null or blank")]  
  11. public int Age{ getset; }  
  12. }  
2. my controller
  1. [HttpPost("api/Student/Check")]  
  2. public async Task Check([FromBody] students input)  
  3. {  
  4. if (!ModelState.IsValid)  
  5. {  
  6. returnBadRequest(Modelstate);  
  7. }  
  8. else {  
  9. returnOk();  
  10. }  
  11. }  
3. created one class for ValidatorActionFilter.cs
  1. public class ValidatorActionFilter : IActionFilter  
  2. {  
  3. public void OnActionExecuting(ActionExecutingContext filterContext)  
  4. {  
  5. if (!filterContext.ModelState.IsValid)  
  6. {  
  7. filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);  
  8. }  
  9. }  
  10. public void OnActionExecuted(ActionExecutedContext filterContext)  
  11. {  
  12. }  
  13. }  
startup.cs
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3. services.AddMvc(options =>  
  4. {  
  5. options.Filters.Add(typeof(ValidatorActionFilter));  
  6. });  
  7. }  

Answers (2)