2

I get the following default standard error message with a bad request response whenever the query parameter page is not valid.

         {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-ase4556503808167887c13a5978d0b-88001bf112e7555d-00","errors":{"page":["The value ''
is invalid."]}}

Similarly when the request body is invalid Json , the framework responds with similar error message as well.

I am catching all the exceptions that are thrown application wide using an ExceptionFilter. How would I capture these particular bad request responses and format them and respond back with custom error format? What kind of Filter, Middleware or ModelBinder should I be using ?

6
  • 1
    You can disable automatic 400 responses by setting SuppressModelStateInvalidFilter to true as described in this Q&A and by Microsoft themselves here Commented Sep 20, 2022 at 6:08
  • 1
    @MindSwipe has provided the correct answer. But note that you should handle the exceptions wisely as you will change the default behavior Commented Sep 20, 2022 at 6:14
  • 1
    You can also refer this stackoverflow.com/q/70110306/6527049 Commented Sep 20, 2022 at 6:16
  • 1
    Hi @RedRose, did you use asp.net web api? If so, you can remove [ApiController] then it will hit the method and you can judge the ModelState.IsValid to choose return custom error. It is better for you to share how is the custom error format you want. And do you want to configure a global error format for 400 bad request? Commented Sep 21, 2022 at 5:39
  • @Rena no I am using asp.net core Commented Sep 21, 2022 at 9:43

1 Answer 1

6

Thank you all for the help, I used a combination of the above comments and were able to solve the issue. It is not ideal but this worked well.

The first thing is to disable the automatic model binder filter like this in your StartUp.cs

        services.Configure<ApiBehaviorOptions>(options =>
        {
           options.SuppressModelStateInvalidFilter = true;
        });

Then, I created an action filter that will execute when ever there is invalid parameter comes from the request:

   public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            var messages = new List<string>();

            actionContext.ModelState.ToList().ForEach(argument => 
            {
                if (argument.Value?.ValidationState == ModelValidationState.Invalid)
                {
                    argument.Value.Errors.ToList().ForEach(error =>
                    {
                        messages.Add(error.ErrorMessage);

                    });
                }
            });

            actionContext.Result = new BadRequestObjectResult(messages);
        }
    }

This will format the response removing all the trace id and urls and only display the message you are looking for, instead of messages you can always create your error object and assign that.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks; This saved me days of research, suppressing the model state invalid filter and handling the validation my self.
Thank you, it means a lot for me to know that I help another fellow developer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.