全局错误处理程序,包括 Model Binder 错误

2023-12-10

我正在开发一个 AspNet Core 3.1 web-api 项目,该项目正在由 PenTest 机构进行测试,当不正确的输入数据导致包含有关项目代码内部信息的响应时,他们会标记情况,如下所示:

{
  "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属性类,并且它可以很好地装饰适当的模型属性。另一个类似的问题是空集合元素导致这种响应,我通过为输入端点参数上的复杂类提供自定义模型绑定器来修复(实现模型绑定器界面)。

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

或者可能有一种配置方法系统.Text.Json为各种类型提供自定义错误消息的功能Json异常发生绑定错误时会抛出什么?


对于模型绑定错误,您可能会在 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);
        };
    }); 
}

Result:

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

全局错误处理程序,包括 Model Binder 错误 的相关文章

随机推荐