【发布时间】:2021-02-10 21:13:52
【问题描述】:
我有一个带有动作的 WebApi 控制器。路由参数之一被强制转换为枚举。但是,如果调用者指定的值无效,则会返回默认错误消息以及 BadRequest HTTP 状态。我的枚举有两个有效值:person/org。例如,如果我传入一个“p”,这就是返回的内容:
{
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",
title: "One or more validation errors occurred.",
status: 400,
traceId: "|cc923491-4f15cb34f96ad64a.",
errors: {
Type: [
"The value 'p' is not valid for Type."
]
}
}
如何指定此转换错误的错误消息?理想情况下,我会在类定义中用一个属性来指定它:
public class Entity
{
// How do I return this as the error message for an incorrect cast of EntityType?
// "entityType must be either 'person' or 'org'."
[Required]
public EntityType Type { get; set; }
[Required]
[Range(1, long.MaxValue, ErrorMessage = "Please specify a valid entity id. Value must be an integer greater than 0.")]
public long Id { get; set; }
}
【问题讨论】:
标签: c# asp.net-web-api2 data-annotations asp.net-core-3.1