我们可以通过任何方式覆盖 asp.net 核心 3.1 中的数据注释响应

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

我有 .net core 3.1 web api 项目。 我已经对我的模型进行了一些数据注释验证。我对验证的回应是

{
  "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"
    ]
  }
}

我可以用任何方式覆盖该响应,例如

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

找到一篇文章,但它似乎与 asp.net core older version 有关 https://www.c-sharpcorner.com/blogs/customizing-model-validation-response-resulting-as-http-400-in-net-core

我已尝试关注但仍然是相同的响应

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
            });
        }

问题在于将 CustomValidationResponse 放置在内部

public void ConfigureServices(IServiceCollection services)

当我上次添加它时它起作用了