zoukankan      html  css  js  c++  java
  • 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

    运行效果

     

  • 相关阅读:
    idea开发工具关于svn上代码的颜色
    写一个Request包装类ExternalApiHttpServletRequestWrapper(外部接口请求使用用于解密)
    什么情况下,需要用事务?
    SpringBoot 2.1.6.RELEASE ->SpringCloudAlibaba
    oracle查看锁表进程,杀掉锁表进程
    JavaScript 闭包
    萤石云定时更新 accessToken
    Ubuntu Linux的DevExpressReport无法显示报表(.net core)
    Vue在IE下打开空白解决方案
    DFT scan chain 介绍
  • 原文地址:https://www.cnblogs.com/chenyinxin/p/8989606.html
Copyright © 2011-2022 走看看