zoukankan      html  css  js  c++  java
  • NetCore入门篇(六):NetCore项目使用Controller之一

    一、简介


    1、当前最流行的开发模式是前后端分离,Controller作为后端的核心输出,是开发人员使用最多的技术点。

    2、个人所在的团队已经选择完全抛弃传统mvc模式,使用html + webapi模式。好处是前端完全复用,后端想换语言,翻译每个api接口即可。

    3、个人最新的框架也是使用这种模式开发,后续会有文章对整个框架进行分析,详见签名信息。

    4、Controller开发时,有几种不同的返回值模式,这里介绍两种常用的。个人使用的是模式二。

    二、Net Core 的 Controller返回值模式一


    1、模式一是在函数定义时直接返回类型,具体看代码,以及运行效果。

    2、分别运行三个函数得到效果。

    这里有个知识点,NetCore对象返回值默认首字母小写。自行对比结果研究下。对象类型在js调用时,是区分大小写的,这里需要对应。

    Controller模式一代码

    public class OneController : Controller
    {
        public string GetString(string id)
        {
            return "string:" + id;
        }
        public Model GetObject(string id)
        {
            return new Model() { ID = id, Name = Guid.NewGuid().ToString() };
        }
        public Dictionary<string, string> GetDictionary(string id)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            result.Add("ID", id);
            result.Add("Name", Guid.NewGuid().ToString());
            return result;
        }
    }
    public class Model
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }

    运行效果

     二、Net Core 的 Controller返回值模式二


    1、模式二是在函数定义返回ActionResult类型,具体看代码,以及运行效果。

    2、分别运行三个函数得到效果。

     Controller模式二代码

    public class TowController : Controller
    {
        public ActionResult GetString(string id)
        {
            return Json("string:" + id);
        }
        public ActionResult GetObject(string id)
        {
            return Json(new Model() { ID = id, Name = Guid.NewGuid().ToString() });
        }
        public ActionResult GetObject2(string id)
        {
            //个人最常用的返回模式,动态匿名类型
            return Json(new { ID = id, Name = Guid.NewGuid().ToString() });
        }
        public ActionResult GetContent(string id)
        {
            return Content("string:" + id);
        }
        public ActionResult GetFile(string id)
        {
            return File("bitdao.png", "image/jpeg");
        }
    }

    运行效果

     

    <返回NetCore入门系列目录

    前往下一篇:NetCore入门篇(七):NetCore项目使用Controller之二>

    斩后知
  • 相关阅读:
    Delphi制作带图标的弹出式选单 DELPHI
    在DBGrid中实现Copy、Paste功能 DELPHI
    使用stringgrid的例子 DELPHI
    取得某一dll所有输出函数名 DELPHI
    HDOJ 2512 一卡通大冒险
    POJ 2533 Longest Ordered Subsequence
    UVA 10795 A Different Task
    HDOJ 1505 City Game
    HDOJ 1864 最大报销额
    HDOJ 1421 搬寝室
  • 原文地址:https://www.cnblogs.com/dyhao/p/14436765.html
Copyright © 2011-2022 走看看