简体   繁体   English

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

[英]How to specify type cast error message for route param error? (C#, WebApi)

I have a WebApi controller with an action.我有一个带有动作的 WebApi controller。 One of the route parameters gets cast to an enumeration.路由参数之一被强制转换为枚举。 However, if the caller specifies a value that's invalid, a default error message is returned with the BadRequest HTTP Status.但是,如果调用方指定的值无效,则会返回默认错误消息,并带有 BadRequest HTTP 状态。 My enum has two valid values: person/org.我的枚举有两个有效值:person/org。 If I pass in a "p" for example, this is what gets returned:例如,如果我传入一个“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."
        ]
    }
}

How can I specify the error message for this cast error?如何指定此转换错误的错误消息? Ideally, I would just specify it with an attribute here in the class definition:理想情况下,我只需在 class 定义中使用属性指定它:

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; }
}

You can use the EnumDataType attribute but it only work if you specify an integer value that doesn't match any of the EntityType enum values.您可以使用EnumDataType属性,但它仅在您指定与任何 EntityType 枚举值都不匹配的 integer 值时才有效。

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

Another thing you can do is create a custom ResultFilterAttribute and handle the error:您可以做的另一件事是创建自定义ResultFilterAttribute并处理错误:

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

Note : you have to register the filter in the FilterCollection of your API注意:您必须在 API 的FilterCollection中注册过滤器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM