iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

.NET Core MVC網頁應用開發系列 第 3

.NET Core第3天_使用CLI來創建.NET Core專案_專案架構解析

預設不管是透過visual studio 或者額外下載安裝完.NET Core SDK

我們能夠利用.NET Core CLI來進行一些程式專案上的開發建置操作
.NET Core版本(可順便確認CLI命令是否正確有被安裝喔)

dotnet --version

https://ithelp.ithome.com.tw/upload/images/20210903/201074524jhGggaq8i.png

.Net Core 可以創建那些專案範本呢?
-l, --list Lists templates containing the specified name. If no name is specified, lists all templates.

dotnet new --list

這是目前3.1版本提供的範本

https://ithelp.ithome.com.tw/upload/images/20210903/20107452tHUQteJEpc.png

創建網站專案
建立一空的 ASP.NET Core Web專案

dotnet new web

dotnet new - 根據指定的範本建立新的專案、組態檔或方案。(可依據創建專案範本類型填入上方表的ShortName)

dotnet new <TEMPLATE> [--dry-run] [--force] [-i|--install {PATH|NUGET_ID}]
    [-lang|--language {"C#"|"F#"|VB}] [-n|--name <OUTPUT_NAME>]
    [--nuget-source <SOURCE>] [-o|--output <OUTPUT_DIRECTORY>]
    [-u|--uninstall] [--update-apply] [--update-check] [Template options]

dotnet new <TEMPLATE> [-l|--list] [--type <TYPE>]

dotnet new -h|--help

https://ithelp.ithome.com.tw/upload/images/20210903/20107452rCLDkJgFrc.png

剛創建的 ASP.NET Core 空專案內容
https://ithelp.ithome.com.tw/upload/images/20210903/20107452wIG2FXtwtv.png

https://ithelp.ithome.com.tw/upload/images/20210903/201074528hnm5zeXRi.png

白話簡單來講
asp.net core應用程式就是一個在Main Method當中建立一個Web 伺服器的簡單主控台應用程式。
以下是以.net core 3.1版本來做學習紀錄

Program.cs
程式進入檔

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

namespace DotNetCoreWebSite
{
    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>();
                });
    }
}

Main method程式的進入點中,透過調用CreateHostBuilder 方法
回傳 IHostBuilder 來配置Configuration,一旦建置應用程式主機,就會指定 Startup 類別(預設執行的初始化腳本),Startup類別通常是藉由在主機建立器上呼叫。
在此我們也能夠自行寫自定義(客製)的初始化腳本。

WebHostBuilderExtensions. webhostbuilder.usestartup 方法來指定
之後 Build 並 Run .NET Core App ,來轉為ASP.NET Core 應用程式。

CreateHostBuilder 呼叫 Host ClassCreateDefaultBuilder

CreateDefaultBuilder() 無參數版本
public static Microsoft.Extensions.Hosting.IHostBuilder CreateDefaultBuilder ();
預設配置執行下列一系列動作
The following defaults are applied to the returned WebHostBuilder:

1.use Kestrel as the web server and configure it using the application's configuration providers
2.set the ContentRootPath to the result of GetCurrentDirectory()
3.load IConfiguration from 'appsettings.json' and 'appsettings.[EnvironmentName].json'
4.load IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly
5.load IConfiguration from environment variables
6.configure the ILoggerFactory to log to the console and debug output
7.adds the HostFiltering middleware, adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, and enable IIS integration.

CreateDefaultBuilder(String[])有參數版本
public static Microsoft.Extensions.Hosting.IHostBuilder CreateDefaultBuilder (string[] args);

The following defaults are applied to the returned WebHostBuilder:
1.use Kestrel as the web server and configure it using the application's configuration providers
2.set the ContentRootPath to the result of GetCurrentDirectory()
3.load IConfiguration from 'appsettings.json' and 'appsettings.[EnvironmentName].json'
4.load IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly
5.load IConfiguration from environment variables
6.load IConfiguration from supplied command line args
7.configure the ILoggerFactory to log to the console and debug output
8.adds the HostFiltering middleware, adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, and enable IIS integration.

然後呼叫ConfigureWebHostDefaults使用默認值配置Web Host 建立 Web 的預設組態環境,包含 ASP.NET Core 如何去處理 Web Server、Config檔、Routing等,或是你可以再自己加其他預設設定。舉例來說,ASP.NET Core 預設會去載入 appsetting.json 設定。如果你要更改或加入其他參考,可以用webBuilder呼叫ConfigureAppConfiguration方法來加入其他參考。

Startup.cs
啟動網站設定
於官方網站定義為「應用程式啟動」設定服務和應用程式的要求管線
應用程式啟動時,ASP.NET Core 會於runtime期間呼叫 ConfigureServices 與 Configure
一般會將要設定的應用程式方法定義於此類別中,在Startup類別中必須定義Configure方法
至於ConfigureServices則可選擇性定義

using System;
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.Hosting;

namespace DotNetCoreWebSite
{
    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("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

Configure 方法
public abstract void Configure (Microsoft.AspNetCore.Builder.IApplicationBuilder app);

將每個服務以中介軟體(中間件、Middleware)方式註冊,具有調整彈性
註冊的順序會影響請求事件發生的結果

再白話一點說就是
用於指定asp.net應用程式將如何回應每一次的HTTP請求。

預設產生的Configure 方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
其實也可自訂的Configure方法參數
必須傳入一IApplicationBuilder 參數
和一些額外的服務,例如 IWebHostEnvironment , ILoggerFactory...etc

藉由將中介軟體元件新增至 IApplicationBuilder 執行個體,即可設定要求管線。 IApplicationBuilder 可用於 Configure 方法,
但它未註冊在服務容器中。 裝載會建立 IApplicationBuilder,並將它直接傳遞到 Configure。

在Configure 方法當中會看到
app.UseDeveloperExceptionPage()
app.UseRouting()
app.UseEndpoints()
...
這裡的app.UseXXX 就是在組裝一系列的中介軟體(Middleware)
每一個Use擴充method都會將一個中介軟體加到請求管線當中

ConfigureServices 方法
public virtual void ConfigureServices (Microsoft.Extensions.DependencyInjection.IServiceCollection services);

由主機在 Configure 方法之前呼叫,來設定應用程式的服務。
在這方法中主要是去設定網站所需的服務
這函數執行生命週期在Configure之前
預設呼叫的方法Pattern為Add{Service}
可使用IServiceCollection加入所需的服務
用於註冊DI服務的地方

DotNetCoreWebSite.csproj
專案檔

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>

appsettings.Development.json
開發階段的 執行程式組態設定

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

appsettings.json
預設 執行程式組態設定

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

若用visual studio 創建.net core 3.1則會看到 一樣的專案架構
而使用中斷點則運行順序如下

https://ithelp.ithome.com.tw/upload/images/20210903/20107452a1pdeB6qAv.png
http://www.binaryintellect.net/articles/4fb59b82-a2a8-41ce-a55f-0a0a28cd6cbc.aspx

至於用vs code測試的由於預設無法下中斷點
需要額外裝套件
https://ithelp.ithome.com.tw/upload/images/20210903/201074522owIGPURpC.png

Ref:

https://docs.microsoft.com/zh-tw/dotnet/core/tools/dotnet-new
WebHost.CreateDefaultBuilder Method
https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.webhost.createdefaultbuilder?view=aspnetcore-3.1

[鐵人賽Day03] - 建立ASP.Net Core MVC專案
https://ithelp.ithome.com.tw/articles/10202806

本文同步發表致個人部落格
https://coolmandiary.blogspot.com/2020/11/net-coreclinet-core.html


上一篇
.NET Core第2天_.NET Core應用程式佈署_Azure平台版
下一篇
.NET Core第4天_middleware是捨麼?
系列文
.NET Core MVC網頁應用開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言