.NET Core第8天_路由端點的切換_注入MVC服務_利用middleware來啟用靜態資源設置預設網址路由

 當新增好一個.net5的 web空專案後


預設進入點位於Program.cs當中的Main() method
C#程式呼叫了CreateHostBuilder() 建立虛擬主機後
在當中call ConfigureWebHostDefaults() 將web server 指地為Kestrel Server
(.net core預設跨平台server)
並指定啟動的類別為Startup

在此篇有做更深入的探討

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!");
                });
            });
        }
    }
}





於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














在新生成的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檢視)


新增檢視項目(這裡選擇的是Razor檢視-空白)



預設默認會幫你選好檢視檔案的名稱Index



自動生成Views目錄下對應Home控制器名稱的folder有我們剛剛選定的Razor檢視檔
但空空的沒有產生預設的內容



如果剛剛新增檢視項目這裡選擇的是Razor檢視


則預設會幫你產出一些html標準外框



那可以看到預設就會導向 MVC Home路由指定的View
並可以看到ViewBag顯示的當前時間



若沒有把預設產生的HelloWord的路由終端 MapGet
註解掉預設則會是指向Hello World文字內容呈現




接著來加入一些靜態資源(比如圖片檔)
由於這種靜態資源必須要放置於wwwroot目錄之下
因此要先建立該目錄(預設會是地球的icon)

於wwwroot再新增一個目錄叫images或assets
加入圖檔後可直接拖拉至cshtml檔案會自動產生img tag

執行後即可展示靜態圖檔資源

















留言

這個網誌中的熱門文章

SAP物料主數據(Material Master Data)

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

外貿Payment Term 付款條件(方式)常見的英文縮寫與定義