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

简介: 原文:ASP.NET Core 配置 MVC - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 MVC 前面几章节中,我们都是基于 ASP.

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

ASP.NET Core 配置 MVC

前面几章节中,我们都是基于 ASP.NET 空项目 模板创建的 HelloWorld 上做开发

通过这个最基本的 HelloWorld 项目,我们了解了很多知识,初窥了 ASP.NET Core,并对 ASP.NET Core 的运行机制有了一个基本的了解

MVC 模式是 Web 开发中最重要的一个模式之一,通过 MVC,我们可以将控制器、模型和视图区分开来

ASP.NET Core 同样支持 MVC 模式,而且是通过中间件的形式来支持 MVC 模式的开发

MVC 中间件

一般情况下,ASP.NET Core 2.1 内置并下载了 Microsoft.AspNetCore.Mvc 程序集

所以我们并不需要使用 NuGet 来做一些额外的安装

我们只需要给我们的应用程序中注册 Microsoft.AspNetCore.Mvc 中间件即可

配置 MVC 中间件

我们需要将 ASP.NET Core MVC 所需的所有服务注册到运行时中

我们在 Startup 类中的 ConfigureServices() 方法中执行此操作

注册完毕后,我们将添加一个简单的控制器,然后使用控制器做一些简单的输出

  1. 我们先在跟目录下创建一个目录 Controllers 目录,用于存放所有的控制器

    右键点击 HelloWorld 项目,然后选择 添加 -> 新建文件夹,并把文件夹命名为 Controllers

  2. 添加完成后 解决方案资源管理器 中显示如下

  3. 右键点击 Controllers 目录,然后选择 添加 -> 新建文件 打开新建文件对话框

    如果你的电脑是 Windows ,则是 添加 -> 新建项

  4. 在新建文件对话框中,选中左边的 General,然后选中右边的 空类

    如果你的电脑是 Windows ,则是先选中 ASP.NET Core 下的 代码 , 然后选中

  5. 在名称中输入 HomeController,然后点击右下角的 新建 按钮,创建一个 HomeController.cs 文件

    如果你的电脑是 Windows ,则是点击右下角的 新建 按钮

  6. 添加完成后 解决方案资源管理器 中显示如下

  7. 同时可以看到 HomeController.cs 中的内容如下

    using System;
    namespace HelloWorld.Controllers
    {
        public class HomeController
        {
            public HomeController()
            {
            }
        }
    }
    
  8. 接下来我们将设置 HomeController 类为我们的默认控制器,也就是访问 / 时默认使用 HomeController 来处理

  9. 修改 HomeController.cs 文件,为类 HomeController 类添加一个 Index() 方法

    public string Index()
    { 
        return "你好,世界! 此消息来自 HomeController..."; 
    }
    

    文件全部内容如下

    using System;
    namespace HelloWorld.Controllers
    {
        public class HomeController
        {
            public HomeController()
            {
            }
    
            public string Index()
            { 
                return "你好,世界! 此消息来自 HomeController..."; 
            }
        }
    }
    
  10. 保存 **HomeController.cs文件,重新启动应用并刷新浏览器,显示的仍然是index.html` 中的内容

  11. 现在,我们删除 wwwroot 目录下的 index.html 文件

    右键点击 index.html 文件,然后选择 删除,在弹出的对话框中点击 删除 按钮

  12. 然后我们回到 Startup.cs 文件中,在 Configure() 方法中的 app.UseFileServer(); 语句后面添加一条语句 app.UseMvcWithDefaultRoute();

    Startup.cs 文件全部代码如下

    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Configuration;
    
    namespace HelloWorld
    {
        public class Startup
        {
            public Startup() 
            { 
                var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("AppSettings.json");
                Configuration = builder.Build(); 
            }
    
            public IConfiguration Configuration { get; set; }
    
            // 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)
            {
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseFileServer();
                app.UseMvcWithDefaultRoute();
    
                /*
                app.Run(async (context) =>
                {
                    var msg = Configuration["message"];
                    await context.Response.WriteAsync(msg);
                });
                */
            }
        }
    }
    
  13. 保存 Startup.cs 文件,重新启动应用,会发现启动失败,出错如下

    System.InvalidOperationException: "Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc' inside the call to 'ConfigureServices(...)' in the application startup code."
    

    意思是 ASP.NET Core 没有找到必须的 Mvc 服务

    ASP.NET 核心框架本身由具有非常专注的责任的不同小型组件组成

    例如,有一个组件必须定位和实例化控制器,但该组件需要位于 ASP.NET Core MVC 的服务集合中才能正常运行

注册 MVC 服务

为了在 ASP.NET Core 中使用 MVC 模式,我们必须在 Startup 类中的 ConfigureServices 方法中添加 AddMvc 服务

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

添加成功后,完整的 Startup.cs 文件如下

using System;
using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace HelloWorld { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } // 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, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseFileServer(); app.UseMvcWithDefaultRoute(); /*  app.Run(async (context) =>  {  var msg = Configuration["message"];  await context.Response.WriteAsync(msg);  });  */ } } } 

保存 Startup.cs 文件,重新启动应用,刷新浏览器,终于可以看到结果了

 
目录
相关文章
|
7天前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
|
7天前
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
21 3
|
29天前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
28 7
|
29天前
|
开发框架 NoSQL .NET
利用分布式锁在ASP.NET Core中实现防抖
【9月更文挑战第5天】在 ASP.NET Core 中,可通过分布式锁实现防抖功能,仅处理连续相同请求中的首个请求,其余请求返回 204 No Content,直至锁释放。具体步骤包括:安装分布式锁库如 `StackExchange.Redis`;创建分布式锁服务接口及其实现;构建防抖中间件;并在 `Startup.cs` 中注册相关服务和中间件。这一机制有效避免了短时间内重复操作的问题。
|
27天前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
38 0
|
2月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
36 0
|
5月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
158 0
|
5月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
68 0
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
155 0
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
93 0