首页 > 解决方案 > 我们可以在 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 旧版本有关 https://www.c-sharpcorner.com/blogs/customizing-model-validation-response-resulting-as-http-400-in-net-核

我尝试了以下但仍然相同的响应

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

标签: data-annotationsasp.net-core-3.1

解决方案


问题是在里面放置 CustomValidationResponse

public void ConfigureServices(IServiceCollection services)

当我最后添加它时,它起作用了


推荐阅读