简体   繁体   中英

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.

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 .

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