.Net Web API 004 Controller獲取對象列表,傳入數據以及對象
2023-08-02 22:04:26 來源:博客園
1、返回UserEntityList
(資料圖)
這個服務接口的目的是分為用戶列表,代碼如下所示。
////// 得到用戶列表/// ///[HttpGet][Route("GetUserList")]public ActionResult > GetUserList(){ var myUserEntityList = new List
() { new UserEntity(){ GUID="A",UserName="AA",Password="", Tel="AAA"}, new UserEntity(){ GUID="B",UserName="BB",Password="", Tel="BBB"}, new UserEntity(){ GUID="C",UserName="CC",Password="", Tel="CCC"}, new UserEntity(){ GUID="D",UserName="DD",Password="", Tel="DDD"}, new UserEntity(){ GUID="E",UserName="EE",Password="", Tel="EEE"}, }; return this.Ok(myUserEntityList);}
通過Url地址訪問,得到的結果如下圖所示。
2、更新密碼
更新密碼操作需要傳入多個參數,這種情況下,需要傳入多個參數。服務的代碼如下所示。
////// 修改密碼/// ///[HttpPost][Route("ChangePassword")]public ActionResult ChangePassword(string pUserGUID, string pOldPassword, string pNewPassword){ //先判斷新密碼格式是否合規 var myNewPassword = pNewPassword.Trim(); if (myNewPassword.Length == 0) { return this.BadRequest("新密碼不能為空。"); } //先讀取用戶的信息,判斷傳入的舊密碼是否正確,正常要從數據庫中讀取 if (pOldPassword != "123456") { return this.BadRequest("原始密碼錯誤。"); } return this.Ok("密碼修改成功" + pUserGUID);}
因為是修改密碼,所以這個API定義為Post,傳入的值都是簡單類型,可以直接附屬到Url后面,不需要定義消息體。編譯后,swagger界面如下圖所示。
執行測試,效果如下圖所示。
3、添加用戶傳入一個UserEntity
在添加用戶或者更新用戶信息的時候,需要傳入一個UserEntity對象,也就是說我們寫的API需要接受一個UserEntity。以添加用戶為例,代碼如下所示。
////// 添加用戶/// ///[HttpPost][Route("AddUser")]public ActionResult AddUser(UserEntity pUserEntity){ if (pUserEntity == null) { return this.BadRequest("請傳正確的UserEntity對象。"); } if (pUserEntity.GUID == "") { pUserEntity.GUID = Guid.NewGuid().ToString(); } return this.Ok("成功添加了名稱為" + pUserEntity.UserName + "的用戶。");}
在swagger中測試,會提供傳入的數據格式實例。如下圖所示。
我們構造一個數據。
{ "guid": "guid", "userName": "TestName", "tel": "手機號碼"}執行,結果如下圖所示。
關鍵詞:
