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

本文介绍了当前流行的前后端分离模式下,NetCore框架中Controller的两种常见返回值模式。第一种模式直接定义返回类型,第二种模式则统一返回ActionResult类型,并通过Json方法返回具体数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一、简介


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

 

运行效果

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/chenyinxin/p/8989606.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值