Asp net core web API, I am trying to return a custom response for the model validator. But ValidateModelFilter is not called when the required field, not in the request.
ValidateModelFilter.cs
public class ValidateModelFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var response = new Model
{
error = context.ModelState.ToString()
};
context.Result = new BadRequestObjectResult(response);
}
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.Filters.Add(typeof(ValidateModelFilter)));
}
I am getting a response like this
{
"errors": {
"Firstname": [
"The Firstname field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|e6752549-4142e91f1074e978."
}
I want to return a response like
{
"error": "The Firstname field is required."
}