User1838940990 posted
Hi All,
In our asp.net core web api 3.1 , we are having validation for models.
If we give SumInsured the maximum range 200000, if we pass 300000 , it give the below response
{
"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 this in action fitler or exception filter before sending the response.
below is the implementation of Action filter in my code.
Can you please let me know your thoughts on this , please correct me if I am wrong any where
--Model
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; }
}
---ActionFilter
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 in startup
services.AddControllers(options => {
options.Filters.Add(new ApiExceptionFilter());
options.Filters.Add(new ValidationFilterAttribute());
});