每日踩坑 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         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM