我在一个由 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提供自定义错误消息?