79252452

Date: 2024-12-04 19:16:28
Score: 1
Natty:
Report link

Thanks for @Parsa99 - he suggested the answer. For anyone who will try to find in in the future, I will post here an example that I was found in the internet.

services.AddControllers(options =>
            {
                options.Filters.Add<ApiErrorFilter>();
            })
            .ConfigureApiBehaviorOptions(opt=>
            {
                opt.SuppressModelStateInvalidFilter = false;
                opt.InvalidModelStateResponseFactory = context=>{
                
                    bool knownExceptions = context.ModelState.Values
                    .SelectMany(x => x.Errors)
                    .Where(x => x.Exception is JsonException || (x.Exception is null && String.IsNullOrWhiteSpace(x.ErrorMessage) == false)).Count() > 0;
                    if (knownExceptions)
                    {
                        var error = new ProblemDetails
                        {
                            Status = (int)HttpStatusCode.InternalServerError,
                            Title = "Test",
                        };

                            return new ObjectResult(error)
                        {
                            StatusCode = StatusCodes.Status422UnprocessableEntity,
                        }; //new BadRequestResult(new { state = false, message = "InvalidParameterError" });
                    }
                // ...
                    return new BadRequestObjectResult(context.ModelState);
                };
            })
            .AddJsonOptions(DefaultJsonOptions.OptionsConfiguration);

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Parsa99
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: JamesBondCaesar