Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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."
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

The link shows how we have to disable the default Model Binding Exception filter that is returning a 400 error and short circuits the pipeline. Only then the OnActionExecuting method in our custom ActionFilterAttribute is actually getting executed. Everything then works as expected.

https://stackoverflow.com/a/51522487/14924779


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...