从零开始学习ASP.NET CORE(九)MVC

MVC介绍

MVC适用于实现应用程序的用户界面层的构架设计模式

  • Model(模型):包含一组数据的类和管理该数据的逻辑信息
  • View(视图):包含显示逻辑,用于显示Controller提供给它的模型中数据
  • Controller(控制器):处理Http请求,调用模型,请选择一个视图来呈现该模型

逻辑顺序,就是一个Request过来,会进入Controller,Controllrer去Model调取数据,然后将数据让View形成视图,Respones返回给用户

MVC初步展示运行

建立空项目,在startup里面写入如下代码

public class Startup
    {
    // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvcWithDefaultRoute();//添加Mvc默认路由的中间件

            app.UseRouting();

            app.Run(async (content) =>
            {
                await content.Response.WriteAsync("hello world");
            });
        }
    }

在项目下面添加Controllers文件夹,再在文件夹下面添加一个控制器,可以右键里面有个控制器,点击进行添加就行,添加一个HomeController类名的控制器,添加的文件示例和里面代码如下:
在这里插入图片描述

using Microsoft.AspNetCore.Mvc;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

修改HomeController代码为如下:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        public string Index()
        {
            return "第一个MVC返回值";
        }
    }
}

点击运行,如果报如下错误,则需要添加下面的代码
在这里插入图片描述

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(option=>option.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvcWithDefaultRoute();

            app.UseRouting();

            app.Run(async (content) =>
            {
                await content.Response.WriteAsync("hello world");
            });
        }
    }

路由后面加上/Home/Index/是一样的结果
在这里插入图片描述

总结和讲解

1、ConfigureServices和Configure的作用
正如生成项目以后,这两个方法上面的英文注解一样,给了解释,ConfigureServices其实就是,用户可以通过这个方法,添加一些服务到容器中,比如Mvc服务,Configure这个方法主要是去配置一些HTTP请求的管道,也就是之前课程说的中间件
2、Mvc有两个步骤,第一,讲所需的MVC服务添加到asp.net core中的依赖注入容器中,就是AddMvc方法;第二,添加MVC中间件到我们的请求处理管道中,就是UseMvcWithDefaultRoute方法。
3、可以看usemvcwithdefaultroute方法的定义注解,默认的路由为Home/Index,id后面加?是可有可无的意思

//
        // 摘要:
        //     Adds MVC to the Microsoft.AspNetCore.Builder.IApplicationBuilder request execution
        //     pipeline with a default route named 'default' and the following template: '{controller=Home}/{action=Index}/{id?}'.
        //
        // 参数:
        //   app:
        //     The Microsoft.AspNetCore.Builder.IApplicationBuilder.
        //
        // 返回结果:
        //     A reference to this instance after the operation has completed.
        public static IApplicationBuilder UseMvcWithDefaultRoute(this IApplicationBuilder app);

2、AddMvc和AddMvcCore的区别
可以发现,不仅有Mvc这个服务,还有MvcCore这个服务,可以查看微软的源代码链接: https://github.com/aspnet/Mvc/blob/release/2.2/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs
AddMvcCore()方法只会添加最核心的MVC服务,AddMvc这个服务里面包含了AddMvcCore()的服务,另外还有其他必须的服务

/// <summary>
        /// Adds MVC services to the specified <see cref="IServiceCollection" />.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <returns>An <see cref="IMvcBuilder"/> that can be used to further configure the MVC services.</returns>
        public static IMvcBuilder AddMvc(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var builder = services.AddMvcCore();

            builder.AddApiExplorer();
            builder.AddAuthorization();

            AddDefaultFrameworkParts(builder.PartManager);

            // Order added affects options setup order

            // Default framework order
            builder.AddFormatterMappings();
            builder.AddViews();
            builder.AddRazorViewEngine();
            builder.AddRazorPages();
            builder.AddCacheTagHelper();

            // +1 order
            builder.AddDataAnnotations(); // +1 order

            // +10 order
            builder.AddJsonFormatters();

            builder.AddCors();

            return new MvcBuilder(builder.Services, builder.PartManager);
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET Core MVC是一种用于构建Web应用程序的开发框架,具有轻量级、高扩展性和性能优越等特点。下面我将简要介绍ASP.NET Core MVC的入门到精通过程。 入门阶段:首先,你需要掌握C#编程语言和基本的Web开发知识。然后,你可以开始学习ASP.NET Core MVC的基本概念,包括请求-响应模型、控制器、视图和模型等。通过创建简单的应用程序,你可以了解到ASP.NET Core MVC的基本工作原理和项目结构。 进阶阶段:在掌握了基本概念后,你可以深入学习路由、过滤器、身份验证和授权等高级特性。此外,了解如何使用数据库和ORM(对象关系映射)框架与数据进行交互也十分重要。在这个阶段,你可以尝试开发更复杂的应用程序,并学习如何优化性能和处理错误。 精通阶段:在掌握了ASP.NET Core MVC的核心概念和高级特性后,你可以进一步提升你的技能。你可以学习如何使用视图组件、自定义标签帮助器和中间件等扩展ASP.NET Core MVC的能力。此外,学习如何进行单元测试和集成测试,以及如何使用日志记录和性能监控工具等也是非常有价值的。 总结起来,要将ASP.NET Core MVC从入门到精通,你需要通过实践来不断巩固你的知识,并深入研究不同的方面和扩展。除此之外,参与开发社区和读一些相关的技术书籍也是提高你的技能和认识的好途径。希望这些信息对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值