1

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:

  1. http://localhost:58984/api/getName/1 - Resolving it to FeMale
  2. http://localhost:58984/api/getName/6 - it is accepting 6 but I would like to throw an exception.
Balanjaneyulu K
  • 3,660
  • 5
  • 24
  • 45
  • 2
    Possible duplicate of [MVC4 WebAPI reject invalid enum values](https://stackoverflow.com/questions/16082062/mvc4-webapi-reject-invalid-enum-values) – Liam Mar 01 '19 at 09:24
  • Check https://stackoverflow.com/q/39789818/5236014 – mukesh kudi Mar 01 '19 at 09:26

1 Answers1

1

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.

dannybucks
  • 2,217
  • 2
  • 18
  • 24
  • It is already an enum, not a string. In order to use TryParse() we had to make a gender.ToString() and parse again. Why is TryParse the better option then? And wouldn't that be Enum.TryParse()? – dannybucks Mar 01 '19 at 09:43
  • I take it back, I didn't realise web api would turn the enum into a integer if it was invalid. – Liam Mar 01 '19 at 09:52
  • By the way: It tried the Enum.TryParse() and that does actually not work, see [demo here](https://dotnetfiddle.net/gcrZ1z). Invalid numbers can still be parsed. And this seems to be the normal behavior as this [answer](https://stackoverflow.com/a/35117297/4636870) states. – dannybucks Mar 01 '19 at 09:58