一、簡介
1、當前最流行的開發模式是前后端分離,Controller作為后端的核心輸出,是開發人員使用最多的技術點。
2、個人所在的團隊已經選擇完全拋棄傳統mvc模式,使用html + webapi模式。好處是前端完全復用,后端想換語言,翻譯每個api接口即可。
3、個人最新的框架也是使用這種模式開發,后續會有文章對整個框架進行分析,詳見簽名信息。
4、Controller開發時,有幾種不同的返回值模式,這里介紹兩種常用的。個人使用的是模式二。
二、Net Core 的 Controller返回值模式一
1、模式一是在函數定義時直接返回類型,具體看代碼,以及運行效果。
2、分別運行三個函數得到效果。
這里有個知識點,NetCore對象返回值默認首字母小寫。自行對比結果研究下。對象類型在js調用時,是區分大小寫的,這里需要對應。
Controller模式一代碼

1 public class OneController : Controller 2 { 3 public string GetString(string id) 4 { 5 return "string:" + id; 6 } 7 public Model GetObject(string id) 8 { 9 return new Model() { ID = id, Name = Guid.NewGuid().ToString() }; 10 } 11 public Dictionary<string, string> GetDictionary(string id) 12 { 13 Dictionary<string, string> result = new Dictionary<string, string>(); 14 result.Add("ID", id); 15 result.Add("Name", Guid.NewGuid().ToString()); 16 return result; 17 } 18 } 19 public class Model 20 { 21 public string ID { get; set; } 22 public string Name { get; set; } 23 }
運行效果
二、Net Core 的 Controller返回值模式二
1、模式二是在函數定義返回ActionResult類型,具體看代碼,以及運行效果。
2、分別運行三個函數得到效果。
Controller模式二代碼

1 public class TowController : Controller 2 { 3 public ActionResult GetString(string id) 4 { 5 return Json("string:" + id); 6 } 7 public ActionResult GetObject(string id) 8 { 9 return Json(new Model() { ID = id, Name = Guid.NewGuid().ToString() }); 10 } 11 public ActionResult GetObject2(string id) 12 { 13 //個人最常用的返回模式,動態匿名類型 14 return Json(new { ID = id, Name = Guid.NewGuid().ToString() }); 15 } 16 public ActionResult GetContent(string id) 17 { 18 return Content("string:" + id); 19 } 20 public ActionResult GetFile(string id) 21 { 22 return File("bitdao.png", "image/jpeg"); 23 } 24 }
運行效果