• NetCore入门篇:(六)Net Core项目使用Controller之一


    一、简介


    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     }
    View Code

    运行效果

     二、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     }
    View Code

    运行效果

     

  • 相关阅读:
    LeetCode 32. 最长有效括号(Longest Valid Parentheses)
    LeetCode 141. 环形链表(Linked List Cycle)
    LeetCode 160. 相交链表(Intersection of Two Linked Lists)
    LeetCode 112. 路径总和(Path Sum)
    LeetCode 124. 二叉树中的最大路径和(Binary Tree Maximum Path Sum)
    LightGBM新特性总结
    sql service 事务与锁
    C#泛型实例详解
    C# 中的委托和事件(详解)
    C# DateTime日期格式化
  • 原文地址:https://www.cnblogs.com/chenyinxin/p/8989606.html
Copyright © 2020-2023  润新知