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

时间:2022-09-16 09:53:50

一、简介


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; }
}

运行效果

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

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

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

二、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入门篇:(六)Net Core项目使用Controller之一

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

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

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

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