当正文中的枚举值无效时,如何在 .NET API 中显示更有意义的错误

问题描述 投票:0回答:1

我有一个 API 端点,其中主体有一个

enum
。如果
enum
的值无效,用户将收到一个有点难以理解的错误(在我看来),例如:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-c3a28ee05a95aadf993ebcf7ecaea7d4-66d04142a844f335-00",
    "errors": {
        "command": [
            "The command field is required."
        ],
        "$.type": [
            "The JSON value could not be converted to System.Nullable`1[Domain.EnumType]. Path: $.type | LineNumber: 14 | BytePositionInLine: 18."
        ]
    }
}

为了与类似的错误保持一致,我更喜欢类似的内容:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "Value": [
            "value [badvalue] is invalid."
        ]
    }
}

虽然我知道我可以通过将类型从

enum
更改为
string
来获得此行为,但我不想这样做,因为我们使用
swagger
并使用枚举,
swagger
能够显示可能的情况枚举值,我认为这是有价值的。

我想知道是否有可能在

.NET
中无需太多努力即可既具有使用枚举的好处(清楚地指示允许的值),又在该值不是有效时具有易于理解的错误消息
enum
.

感谢您的帮助和建议, 埃里克

.net enums swagger
1个回答
0
投票

您可以尝试使用自定义验证属性来解决此问题。

  1. 在IsValid方法中检查Enum值是否有效
  2. 更新FormatErrorMessage中的错误消息
© www.soinside.com 2019 - 2024. All rights reserved.