简体   繁体   中英

ASP.NET Core Web API - How to validate based on specified value using data annotation

In ASP.NET Core-6 Web API, I just decide to use data annotation for validation. I have this code:

public class EnumList
{
    public enum ChargeMode : byte
    {
        None = 0,
        Fixed = 1,
        Percentage = 2
    }
}

DTO:

public class CustomerDto
{
    [Required]
    public ChargeMode ChargeMode { get; set; }     // None = 0, Fixed = 1, Percentage = 2
}

How do I validate ChargeMode in the CustomerDto based on any of the values coming from ChargeMode coming from EnumList?

Thanks

If you post a value don't match the format you'll get 400 error

but if you pass an int value out of range,you'll get the value you send rather than"None","Fixed","Percentage"

So You could try add [Range(0, 2,ErrorMessage = "Value for {0} must be between {1} and {2}.")] Attribute to prevent the value out of range

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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