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

问题描述

我正在研究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."
    ]
  }
}

因此,我们决定使用中性的内容(例如“错误的输入数据”)来更改“错误/$.flags”属性的消息。

我通过提供自定义的 JsonConverter 属性类对这种特殊情况进行了分类,并且为适当的模型属性进行修饰后效果很好。我通过在输入端点参数( IModelBinder 接口的实现)上为复杂类提供自定义模型绑定程序来解决另一个类似的问题,即空的集合元素会导致此类响应。

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

或者也许有一种方法可以配置 System.Text.Json 功能,以便为在绑定错误的情况下抛出的所有 JsonExceptions 提供自定义错误消息?

解决方法

对于模型绑定错误,您可以在asp.net核心网络api中收到400错误的请求。我建议您可以自定义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."; 
    }
}

Startup.cs:

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

结果:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...