Reformatting default asp.net core bad request error message

Viewed 41

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 happen 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 ?

1 Answers

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.

Related