微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为路由参数错误指定类型转换错误消息? (C#, WebApi)

如何解决如何为路由参数错误指定类型转换错误消息? (C#, WebApi)

我有一个带有动作的 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; }
}

解决方法

您可以使用 EnumDataType 属性,但它仅在您指定的整数值与任何 EntityType 枚举值都不匹配时才有效。

[EnumDataType(typeof(EntityType ),ErrorMessage = "Please specify a valid EntityType.")]

您可以做的另一件事是创建自定义 ResultFilterAttribute 并处理错误:

public class CustomFilter : ResultFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        // your code
        base.OnResultExecuted(context);
    }
}

注意:您必须在 API 的 FilterCollection 中注册过滤器

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.Filters.Add(new CustomFilter()));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。