每日踩坑 2018-01-09 WebAPI会如何面对 枚举 参数?

这一块确实有些疑问,

众所周知 枚举参数我们传送枚举值所对应的数字就行了,

以前 Leader 跟我讲过,枚举参数会将字符串值也能够成功转化,而且枚举值定义之外的数字也可以被转为枚举值。

主要的问题在于这后一句,如果定义之外的值能够被转换进去,那么我们是要多写些检查逻辑的。

枚举定义

        public enum type
        {
            Unknow = 0,
            xxx = 1,
            yyy = 2,
        }

首先是 GET 方法,使用 URL 来传值。

        [HttpGet]
        [Route("api/test/getlist/{type}")]
        public string[] GetList(type type)
        {
            return new string[] { type.ToString() };
        }

以下的请求都成功的取到值:

http://localhost:32076/api/test/getlist/xxx

http://localhost:32076/api/test/getlist/1

http://localhost:32076/api/test/getlist/5 (是的没错 进去了 头疼,想起我以前很多都没写过检查

以下的请求没能成功的取到值:

http://localhost:32076/api/test/getlist/  (找不到方法

http://localhost:32076/api/test/getlist/xxxx  (请求无效 枚举参数不能为 null

然后使用 POST 和 对象参数

        public class Data
        {
            public int Id { get; set; }

            public string Name { get; set; }

            public type Type { get; set; }
        }


        [HttpPost]
        [Route("api/test/getlist")]
        public string[] GetList(Data Data)

http://localhost:32076/api/test/getlist/  (post 空对象 调用ok,当然参数实例为空。

http://localhost:32076/api/test/getlist/  (post 对象 仅Id传值 调用ok,此时枚举默认值0(关于枚举默认值有很多文章,自行百度。

也就是说我们应该在接口层对枚举进行基本的值范围检查。

我见过很多人写反射来做这个检查。其实枚举类上就有NET为我们准备好的方法·。

送上一个扩展方法:

1         /// <summary>
2         /// 检查枚举的值是否在枚举范围内
3         /// </summary>
4         /// <param name="value"></param>
5         /// <returns></returns>
6         public static bool IsValid(this Enum value)
7         {
8             return Enum.IsDefined(value.GetType(), value);
9         }

猜你喜欢

转载自www.cnblogs.com/Aaxuan/p/10243148.html