Balanjaneyulu K
Balanjaneyulu K

Reputation: 4324

Pass Enum Parameter to WebApi method

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.

Upvotes: 1

Views: 7689

Answers (2)

Vector
Vector

Reputation: 407

It does do that for you. I've experienced it myself. It accepts both the numeric and string value of the enums, validates them, and handles the 400 bad request return result and error message for you. The only thing I wish it did do is provide all the valid enum values in the error message so that a developer can see what needs to change.

See this answer to practically the same question from back in 2017 which still works today on .net 8 and 9:

Best practice for passing enum params in Web API

Upvotes: 0

dannybucks
dannybucks

Reputation: 2355

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.

Upvotes: 0

Related Questions