枚举为ASP.NET Core WebAPI中的必填字段 [英] Enum as Required Field in ASP.NET Core WebAPI

查看:784
本文介绍了枚举为ASP.NET Core WebAPI中的必填字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当JSON请求没有为枚举属性提供适当的值时,是否可能返回[Required]属性错误消息?

Is it possible to return the [Required] attribute error message when a JSON request doesn't provide a proper value for an enum property?

例如,我有一个POST消息模型,其中包含一个枚举类型的AddressType属性:

For example, I have a model for a POST message that contains an AddressType property that is an enumeration type:

public class AddressPostViewModel
{
    [JsonProperty("addressType")]
    [Required(ErrorMessage = "Address type is required.")]
    public AddressType AddressType { get; set; }
}

AddressType枚举接受两个值:

[JsonConverter(typeof(StringEnumConverter))]
public enum AddressType
{
    [EnumMember(Value = "Dropship")]
    Dropship,
    [EnumMember(Value = "Shipping")]
    Shipping
}

我已经注意到(或者实际上我的质量保证团队已经注意到),如果请求消息JSON包含AddressType的空字符串或null,则错误消息不是预期的Address type is required.消息.相反,该错误消息是一种不太友好的解析错误.

I've noticed (or actually my QA team noticed) that if the request message JSON contains either an empty string or null for the AddressType, the error message isn't the expected Address type is required. message. Instead, the error message is a somewhat unfriendly parsing error.

例如,如果请求JSON如下所示:

For example, if the request JSON looks like this:

{  "addressType": "" }

然后,验证框架自动生成的错误如下所示:

Then the error that is auto-generated by the validation framework looks like this:

{
    "message": "Validation Failed",
    "errors": [
        {
            "property": "addressType",
            "message": "Error converting value \"\" to type 'MyNamespace.AddressType'. Path 'addressType', line 4, position 19."
        }
    ]
}

如果某人未包含枚举的有效值,是否可以确保返回[Required]属性的错误消息?

Is there a way to ensure that error message of the [Required] attribute is returned if someone doesn't include a valid value for an enum?

推荐答案

尽管代码使我有些畏缩,但我想出了一个可以满足我的要求的解决方案.

I've come-up with a solution that meets my requirements, although the code makes me cringe a little.

我在视图模型的AddressType属性上保留了[Required]属性.最令人毛骨悚然的部分是我必须将属性设置为nullable:

I kept the [Required] attribute on the AddressType property in the view model. The cringe-worthy part is that I had to make the property nullable:

public class AddressPostViewModel
{
    [JsonProperty("addressType")]
    [Required(ErrorMessage = "Address type is required.")]
    public AddressType? AddressType { get; set; }
}

AttributeType枚举本身上,按照@Manoj Choudhari的建议,我用自定义的JsonConverter替换了StringEnumConverter属性:

On the AttributeType enum itself, I replaced the StringEnumConverter attribute with a custom JsonConverter as suggested by @Manoj Choudhari:

[JsonConverter(typeof(CustomStringToEnumConverter))]
public enum AddressType
{
    [EnumMember(Value = "Dropship")]
    Dropship,
    [EnumMember(Value = "Shipping")]
    Shipping
}

这是CustomStringToEnumConverter:

public class CustomStringToEnumConverter : StringEnumConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (string.IsNullOrEmpty(reader.Value?.ToString()))
        {
            return null;
        }

        object parsedEnumValue;

        var isValidEnumValue = Enum.TryParse(objectType.GenericTypeArguments[0], reader.Value.ToString(), true, out parsedEnumValue);

        if (isValidEnumValue)
        {
            return parsedEnumValue;
        }
        else
        {
            return null;
        }
    }
}

CustomStringToEnumConverter可以处理空字符串,空值和无效字符串.如果遇到无效的枚举值,它将返回null,然后在进行所需的字段验证(魔术)并且在JSON响应中显示RequiredAttribute错误消息时捕获该错误.

The CustomStringToEnumConverter can handle empty strings, nulls, and invalid strings. If it encounters an invalid enum value, it returns null which is then caught when the required field validation (magic) occurs and the RequiredAttribute error message is displayed in the JSON response.

虽然我不喜欢将AttributeType类型设置为可空,但如果请求JSON中的AttributeType值错误,我的API使用者将看到一致的验证消息.

While I don't like making the AttributeType type nullable, the consumer of my API will see a consistent validation message if the AttributeType value is wrong in the request JSON.

这篇关于枚举为ASP.NET Core WebAPI中的必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆