[七] ASP.NET Core MVC 的设计模式

Posted 长不大的大灰狼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[七] ASP.NET Core MVC 的设计模式相关的知识,希望对你有一定的参考价值。

1、MVC

模型(Model),视图(View)、控制器(Controller)。 它是用于实现应用程序的用户界面层的架构设计模式。 一个典型的实际应用程序通常具有以下层:

  • 用户展现层
  • 业务逻辑处理层
  • 数据访问读取层 MVC 设计模式通常用于实现应用程序的用户界面层。

2、MVC 如何工作

  • 当我们的请求到达服务器时,作为 MVC 设计模式下的 Controller,会接收请求并且处理它。Controller 会创建模型(Model),该模型是一个类文件,会进行数据的展示。
  • 在 Molde 中,除了数据本身,Model 还包含从底层数据源(如数据库)查询数据后的逻辑信息。
  • 除了创建 Model 之外,控制器还选择 View 并将 Model 对象传递给该 View。
  • 视图仅负责呈现 Modle 的数据。
  • 视图会生成所需的 html 以显示模型数据,即 Controller 提供给它的学生数据。然后,此 HTML通过网络发送,最终呈现在发出请求的用户面前。

2、在 ASP.NET Core 中安装 MVC

步骤 1: 将所需的 MVC 服务添加到 ASP.NET Core 中的依赖注入容器中。在 Startup.cs 文件中的 Startup 类的ConfigureServices()方法中,加入services.AddMvc();

步骤 2: 在 Configure()方法中,将UseMvcWithDefaultRoute()中间件添加到应用程序的请求处理管道中。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

注意:
UseMvcWithDefaultRoute()中间件之前放置了UseStaticFiles()中间件。因为如果请求是针对静态文件(如图像,CSS 或 javascript 文件),则UseStaticFiles()中间件将处理请求并使管道的其余部分短路。即不会再往下执行。

3、UseMvcWithDefaultRoute()

请求根路径http://localhost:49119,并未在 URL 中指定控制器和操作方法时, UseMvcWithDefaultRoute()中间件会在 HomeController 中查找 Index()方法。

public class HomeController
{
    public string Index()
    {
        return "Hello from MVC";
    }
}

4、AddMvc 和 AddMvcCore 是什么关系

在 Startup 类的 ConfigureServices()方法中可以调用 IServiceCollection 接口的 AddMvc()方法和AddMvcCore()方法。


AddMvcCore()方法只添加核心 MVC 服务。AddMvc()方法添加所有必需的 MVC 服务。AddMvc()方法在内部调用 AddMvcCore()方法,以添加所有核心 MVC 服务。

想要返回 HTML 视图或 JSON 数据, HomeController 类必须继承框架提供的 Controller 类。Controller 基类提供了返回不同结果的支持,如 JsonResult,ViewResult,PartialViewResult 等。

public class HomeController : Controller
{
    public JsonResult Index()
    {
        return Json(new { id=1, name="pragim" });
    }
}

5、ASP.NET Core MVC 中的 Model 模型

实体类:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Major { get; set; }
}

接口:

public interface IStudentRepository
    {
        Student GetStudent(int id);

    }

实现:

public class MockStudentRepository : IStudentRepository
    {
        private List<Student> _studentList;

        public MockStudentRepository()
        {
            _studentList = new List<Student>()
            {
            new Student() { Id = 1, Name = "张三", Major = "一年级", Email = "Tony-zhang@52abp.com" },
            new Student() { Id = 2, Name = "李四", Major = "二年级", Email = "lisi@52abp.com" },
            new Student() { Id = 3, Name = "王二麻子", Major = "二年级", Email = "wang@52abp.com" },
            };
        }


        public Student GetStudent(int id)
        {
            return _studentList.FirstOrDefault(a => a.Id == id);
        }
}

6、ASP.NET Core 中的 依赖注入介绍

使用构造函数将IStudentRepository实例注入HomeController。

public class HomeController : Controller
    {
        private IStudentRepository _studentRepository;

       //使用构造函数注入的方式注入IStudentRepository
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }


       //返回学生的名字
        public string Index()
        {
      return      _studentRepository.GetStudent(1).Name;
        }
}

此时如果有人请求实现IStudentRepository的对象,ASP .NET Core 依赖注入容器不知道要提供哪个对象实例。

ASP.NET Core 提供3 种方法来使用依赖项注入容器注册服务:

  • AddSingleton():所有请求复用一个单例
  • AddTransient():同一个Http请求范围内,每次使用该实例都会创建一个新的实例。
  • AddScoped():同一个Http请求范围内,使用同一个实例,但当又发起一个新请求时,会再次创建一个新的实例。

使用AddSingleton()向 ASP.NET Core 依赖注入容器注册MockStudentRepository类方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
     services.AddSingleton<IStudentRepository, MockStudentRepository>();
}

7、ASP.NET CoreMVC 中的控制器

  • MVC 中的控制器是一个类,它继承自Microsoft.AspNetCore.Mvc.Controller。
  • 控制器类名称后缀为 “Controller”。例如 HomeController,StudentController。
  • 当来自浏览器的请求到达我们的应用程序时,作为 MVC 中的控制器,它会处理传入的 http 请求并响应用户操作。
  • Controller 类包含一组公共方法。Controller 类中的这些公共方法称为操作方法( action methods)。正是这些控制器的操作方法处理传入的 http 请求。
  • 假设用户在浏览器地址栏中键入了以下 URL 并按 ENTER 键http://localhost:12345/home/details
    URL"/home/details"会映射到 HomeController
    中的"Details"公共操作方法。此映射是由我们应用程序中的路由规则定义完成。
  • 请求到达控制器中的方法。作为处理该请求的一部分,控制器创建模型-Model。
  • 控制器通过依赖的服务,来查询模型数据。例如,我们要查询学生的数据,就需要通过 HomeController 依赖的IStudentRepository服务。

注意:
我们将注入的依赖项分配给readonly字段,可以防止在方法中意外地为其分配另一个值。

(1)返回数据
当控制器拥有所需的模型数据,比如我们正在提供服务或 RESTful API,它就可以简单地返回该模型数据。

1)JsonResult返回 JSON 数据,它不接受内容协商并忽略Accept Header。

  public class HomeController:Controller
    {
        private readonly IStudentRepository _studentRepository;
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }
        public JsonResult Details()
        {
            Student model = _studentRepository.GetStudent(1);
            return Json(model);

        }
    }

2)ObjectResult如果请求头Accept Header设置为application/xml,则返回 XML 数据。如果设置为application/json,则返回 JSON 数据。

public class HomeController:Controller
    {
        private readonly IStudentRepository _studentRepository;
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }
       public ObjectResult Details()
        {
            Student model = _studentRepository.GetStudent(1);
            return new ObjectResult(model);

        }
    }

注意:为了能够以 XML 格式返回数据,我们必须通过调用 Startup.cs 文件中的 ConfigureServices()方法中的 AddXmlSerializerFormatters()的方法。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddXmlSerializerFormatters();
}

3)ViewResult返回View:

public class HomeController:Controller
    {
        private readonly IStudentRepository _studentRepository;
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }
          public ViewResult Details()
        {
            Student model = _studentRepository.GetStudent(1);
            return   View(model);
        }
}

以上是关于[七] ASP.NET Core MVC 的设计模式的主要内容,如果未能解决你的问题,请参考以下文章

干货分享:ASP.NET CORE(C#)与Spring Boot MVC(JAVA)异曲同工的编程方式总结

ASP.NET Core MVC I/O编程模型

ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 14. ASP.NET Core Identity 入门

ASP.NET Core 配置 MVC - ASP.NET Core 基础教程 - 简单教程,简单编程

[MVC&Core]ASP.NET Core MVC 视图传值入门

ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 25. 过滤器