1

我在一个由 PenTest 机构测试的 AspNet 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": "00-371d845d720a4f4c8ad3d618e4386125-7086a0b4fb30614c-00",
  "errors": {
    "$.flags": [
      "The JSON value could not be converted to System.Int32. Path: $.flags | LineNumber: 0 | BytePositionInLine: 47."
    ]
  }
}

所以我们决定用一些中性的东西来改变“errors/$.flags”属性的消息,比如“不正确的输入数据”。

我通过提供自定义JsonConverter< int >属性类来整理这个特殊情况,并且它可以很好地为适当的模型属性进行装饰。另一个类似的问题是空集合元素导致这种响应,我通过在输入端点参数(IModelBinder接口的实现)上为复杂类提供自定义模型绑定器来修复。

该项目有很多端点和输入模型类,因此提供自定义 JsonConverters 或模型绑定器看起来无效且不能面向未来,因为每个新端点的输入都需要配备某种解决方案。那么问题来了——是否有可能有某种全局错误处理程序来覆盖模型绑定器错误?中间件中的标准 aspnet 核心错误处理程序无法处理模型绑定器错误,因为它们在实际调用操作之前发生在操作调用逻辑中。

或者可能有一种方法可以配置System.Text.Json功能,为发生绑定错误时抛出的各种JsonExceptions提供自定义错误消息?

4

1 回答 1

2

对于模型绑定错误,您可能会在 asp.net core web api 中得到 400 Bad Request。我建议您可以自定义ValidationProblemDetails显示错误。

public class CustomBadRequest : ValidationProblemDetails
{
    public CustomBadRequest(ActionContext context)
    {
        Title = "Invalid arguments to the API";
        Detail = "The inputs supplied to the API are invalid";
        Status = 400;
        ConstructErrorMessages(context);
        Type = context.HttpContext.TraceIdentifier;
        
    }
    private void ConstructErrorMessages(ActionContext context)
    {
        foreach (var keyModelStatePair in context.ModelState)
        {
            var key = keyModelStatePair.Key;
            var errors = keyModelStatePair.Value.Errors;
            if (errors != null && errors.Count > 0)
            {
                if (errors.Count == 1)
                {
                    var errorMessage = GetErrorMessage(errors[0]);
                    Errors.Add(key, new[] { errorMessage });
                }
                else
                {
                    var errorMessages = new string[errors.Count];
                    for (var i = 0; i < errors.Count; i++)
                    {
                        errorMessages[i] = GetErrorMessage(errors[i]);
                    }
                    Errors.Add(key, errorMessages);
                }
            }
        }
    }
    string GetErrorMessage(ModelError error)
    {
        return "Incorrect input data."; 
    }
}

启动.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var problems = new CustomBadRequest(context);
            return new BadRequestObjectResult(problems);
        };
    }); 
}

结果:

在此处输入图像描述

于 2020-10-14T05:49:25.990 回答