.NET Core第8天_路由端点的切换_注入MVC服务_利用middleware来启用静态资源设置预设网址路由

当新增好一个.net5的 web空专案後

预设进入点位於Program.cs当中的Main() method
C#程序呼叫了CreateHostBuilder() 建立虚拟主机後
在当中call ConfigureWebHostDefaults() 将web server 指地为Kestrel Server
(.net core预设跨平台server)
并指定启动的类别为Startup

在此篇有做更深入的探讨
.NET Core第3天_使用CLI来创建.NET Core专案_专案架构解析

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace prjNet5_2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

可以来测试位於Startup.cs的Configure方法
路由端点改变

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace prjNet5_2
{
    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)
        {
        }

        // 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.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/First", async context =>
                {
                    await context.Response.WriteAsync("First asp.net core app");
                });
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

https://ithelp.ithome.com.tw/upload/images/20210908/201074525s8KuMymag.png

於Startup.cs
当中的ConfigureServices 方法
我们来注入要使用的MVC服务

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

在Configure 方法
利用middleware来启用静态资源
以及预设网址路由

// 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.UseStaticFiles();//启用静态资源可存取性
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{Controller=Home}/{Action=Index}/{id?}"
        );//设置MVC默认路由

        //endpoints.MapGet("/", async context =>
        //{
        //    await context.Response.WriteAsync("Hello World!");
        //});
    });
}

透过MapControllerRoute协助我们设定mvc 路由格式
Controller跟Action还有选择性的id

建立控制器预设要放置於名为Controllers的目录
创建名为Home的Controller

https://ithelp.ithome.com.tw/upload/images/20210908/20107452wQvIe1G9pN.png

https://ithelp.ithome.com.tw/upload/images/20210908/20107452HizAZOeEYB.png

https://ithelp.ithome.com.tw/upload/images/20210908/20107452AbyJFSRcf9.png

在新生成的Controller的Index Action方法中
加上透过ViewBag传递至View显示的现在时间

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace prjNet5_2.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.DisplayCurTime = DateTime.Now.ToString();
            return View();
        }
    }
}

新增检视(跟以前的.net mvc一样直接对Action右键新增Razor检视)
https://ithelp.ithome.com.tw/upload/images/20210908/20107452CHYL9mx1Fb.png

新增检视项目(这里选择的是Razor检视-空白)
https://ithelp.ithome.com.tw/upload/images/20210908/20107452hf5XPwHWFd.png

预设默认会帮你选好检视档案的名称Index
https://ithelp.ithome.com.tw/upload/images/20210908/201074525sK8AJhKgp.png

自动生成Views目录下对应Home控制器名称的folder有我们刚刚选定的Razor检视档
但空空的没有产生预设的内容
https://ithelp.ithome.com.tw/upload/images/20210908/20107452cRLwbX6z3l.png

如果刚刚新增检视项目这里选择的是Razor检视
https://ithelp.ithome.com.tw/upload/images/20210908/20107452bLhz7xV9pW.png

则预设会帮你产出一些html标准外框
https://ithelp.ithome.com.tw/upload/images/20210908/20107452ftTHafjUhx.png

那可以看到预设就会导向 MVC Home路由指定的View
并可以看到ViewBag显示的当前时间
https://ithelp.ithome.com.tw/upload/images/20210908/20107452eyTaSATmtK.png

若没有把预设产生的HelloWord的路由终端 MapGet
注解掉预设则会是指向Hello World文字内容呈现
https://ithelp.ithome.com.tw/upload/images/20210908/20107452tUO8tNC3RY.png

接着来加入一些静态资源(比如图片档)
由於这种静态资源必须要放置於wwwroot目录之下
因此要先建立该目录(预设会是地球的icon)

於wwwroot再新增一个目录叫images或assets
加入图档後可直接拖拉至cshtml档案会自动产生img tag

执行後即可展示静态图档资源
https://ithelp.ithome.com.tw/upload/images/20210908/20107452C55UKQ1e2x.png

本文已同步发表至个人部落格
https://coolmandiary.blogspot.com/2021/07/net-coremvcmiddleware.html


<<:  Day8: [资料结构]Hash Table - 杂凑表

>>:  Spring Framework X Kotlin Day 3 IOC/DI

State 和生命周期(上)(Day5)

在讲到生命周期之前要确认理解前面做过的两件事: setInterval 去更新画面的例子 记得有 c...

【第一天 - CTF介绍】

CTF 全名 Capture The Flag,并且分为下列几类的解题方式 解谜式(Jeopard...

学习MLOps前暖身操:why, what, who?

接下来的30天,我们会一起看MLOps的更多层面。从为什麽产业开始谈MLOps开始,以及其包含的技术...

DAY19 - 在win10家用版上安装Docker Desktop

前言 铁人赛进入第十九天,今天要来讲讲如何用Docker 打造程序开发环境 Docker 的维基百科...

网页储存区 - localStorage & sessionStorage

网页可以储存使用者偏好,可以在关掉网页後重新访问时纪录使用者上次浏览的状态,能做到这些神奇的事是因为...