Any way we can override data annotation response in asp.net core 3.1

Viewed 357

i have .net core 3.1 web api project. I have put some data annottion validation on my models. my response of validation is coming like

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|41a37de5-4212fb57b7a19a61.",
  "errors": {
    "fk_entity_id": [
      "Please enter a value bigger than 0"
    ]
  }
}

any way i can overridde that response like

{
  "success": "failed", 
  "message": "validation error occured", 
  "errors": {
    "fk_entity_id": [
      "Please enter a value bigger than 0"
    ]
  }
}

find one article but it seems to be related to asp.net core older version https://www.c-sharpcorner.com/blogs/customizing-model-validation-response-resulting-as-http-400-in-net-core

I have tried following but still same response

private void CustomValidationResponse(IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(
                options => options.InvalidModelStateResponseFactory = actionContext =>
                {
                    return CustomErrorResponse(actionContext);
                }
                );
        }
        
          private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext)
        {
            var errorRecordList = actionContext.ModelState
              .Where(modelError => modelError.Value.Errors.Count > 0)
              .Select(modelError => new Error
              {
                  ErrorField = modelError.Key,
                  ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
              }).ToList();
            return new BadRequestObjectResult(new
            {
                success = "failed",
                message = "Validation error occured",
                errors = errorRecordList
            });
        }
1 Answers

Problem was placement of CustomValidationResponse inside

public void ConfigureServices(IServiceCollection services)

When i added it in last it worked

Related