Trying to pass enum type value to WebApi but it is accepting any value other than enum integers.
can we restrict to accept only enum values?
public class ValuesController : ApiController
{
[HttpGet]
[Route("api/getName/{Gender}")]
public IEnumerable<string> Get(Gender gender)
{
Gender g = gender;
return new string[] { "value1", "value2" };
}
}
Enum Value
public enum Gender
{
Male,
FeMale
}
Ex:
You have to check this manually, ASP.NET MVC does not to that for you:
Type enumType = gender.GetType();
bool isEnumValid = Enum.IsDefined(enumType, gender);
if (!isEnumValid) {
throw new Exception("...");
}
Instead of throwing an exception, you could also use a validator on the model that checks if the enum is correct.
The reason why the invalid enum is passed in through the parameter is, because enums are integers, explained here.