User1838940990 posted
Hi All,
This about asp.net core web api 3.1
I am trying to handle when the Validation of model field happens
Below mode the maximum range for SumInsured 200000 , if I put 300000 , then it throws a validation error like below
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|90e52394-484e4c602b1e5fec.",
"errors": {
"SumInsured": [
"should be greater than 100000 and less than 200000"
]
}
}
But I am not able to catch here validation error in ActionFilters, UseExceptionHandler extension or custom ExceptionFilter
below is the Action filter implementation
Is there any filters i can access this validation errors before the controller send the response back
public class UserInfo
{
[Required]
[Range(100000,200000,ErrorMessage ="should be greater than {1} and less than {2}")]
public decimal SumInsured { get; set; }
[Required]
public string Name { get; set; }
[Required]
[Range(0,80,ErrorMessage ="Age should be a number than {1} and {2}")]
public int Age { get; set; }
[Required]
public DateTime? DateOfBirth { get; set; }
}
public class ValidationFilterAttribute : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
inject dependencies instartup
services.AddControllers(options => {
options.Filters.Add(new ApiExceptionFilter());
options.Filters.Add(new ValidationFilterAttribute());
});