如何为route param error指定类型转换错误消息?(C#,WebApi)
我有一个带有动作的WebApi控制器。其中一个路由参数被强制转换为枚举。但是,如果调用方指定的值无效,则返回一条默认错误消息,并显示BadRequest HTTP状态。我的枚举有两个有效值:person/org。例如,如果我传入一个“p”,则返回的结果如下:如何为route param error指定类型转换错误消息?(C#,WebApi),c#,asp.net-web-api2,data-annotations,asp.net-core-3.1,C#,Asp.net Web Api2,Data Annotations,Asp.net Core 3.1,我有一个带有动作的WebApi控制器。其中一个路由参数被强制转换为枚举。但是,如果调用方指定的值无效,则返回一条默认错误消息,并显示BadRequest HTTP状态。我的枚举有两个有效值:person/org。例如,如果我传入一个“p”,则返回的结果如下: { type: "https://tools.ietf.org/html/rfc7231#section-6.5.1", title: "One or more validation error
{
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; }
}
您可以使用
EnumDataType
属性,但仅当您指定的整数值与任何EntityType枚举值都不匹配时,该属性才起作用
[EnumDataType(typeof(EntityType),ErrorMessage=“请指定有效的EntityType。”)]
您可以做的另一件事是创建自定义resultfilterate属性
,并处理错误:
公共类CustomFilter:ResultFilterAttribute
{
公共覆盖无效OnResultExecuted(ResultExecutedContext)
{
//你的代码
base.OnResultExecuted(上下文);
}
}
注意:您必须在API的过滤器集合
中注册过滤器
public void配置服务(IServiceCollection服务)
{
services.AddMvc(options=>options.Filters.Add(newcustomfilter());
}