天天看點

ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC

原文: 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

    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  2. 添加完成後 解決方案資料總管 中顯示如下
    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  3. 右鍵點選

    Controllers

    目錄,然後選擇 添加 -> 建立檔案 打開建立檔案對話框

    如果你的電腦是 Windows ,則是 添加 -> 建立項

    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  4. 在建立檔案對話框中,選中左邊的 General,然後選中右邊的 空類

    如果你的電腦是 Windows ,則是先選中 ASP.NET Core 下的 代碼 , 然後選中 類

    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  5. 在名稱中輸入 HomeController,然後點選右下角的 建立 按鈕,建立一個 HomeController.cs 檔案

    如果你的電腦是 Windows ,則是點選右下角的 建立 按鈕

    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  6. ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  7. 同時可以看到

    HomeController.cs

    中的内容如下
    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
    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` 中的内容
    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
  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 檔案,重新啟動應用,會發現啟動失敗,出錯如下
    ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC
    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 檔案,重新啟動應用,重新整理浏覽器,終于可以看到結果了

ASP.NET Core 配置 MVC - ASP.NET Core 基礎教程 - 簡單教程,簡單程式設計ASP.NET Core 配置 MVC

繼續閱讀