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

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

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



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

這是目前3.1版本提供的範本
Templates                                         Short Name               Language          Tags
----------------------------------------------------------------------------------------------------------------------------------
Console Application                               console                  [C#], F#, VB      Common/Console
Class library                                     classlib                 [C#], F#, VB      Common/Library
WPF Application                                   wpf                      [C#]              Common/WPF
WPF Class library                                 wpflib                   [C#]              Common/WPF
WPF Custom Control Library                        wpfcustomcontrollib      [C#]              Common/WPF
WPF User Control Library                          wpfusercontrollib        [C#]              Common/WPF
Windows Forms (WinForms) Application              winforms                 [C#]              Common/WinForms
Windows Forms (WinForms) Class library            winformslib              [C#]              Common/WinForms
Worker Service                                    worker                   [C#]              Common/Worker/Web
Unit Test Project                                 mstest                   [C#], F#, VB      Test/MSTest
NUnit 3 Test Project                              nunit                    [C#], F#, VB      Test/NUnit
NUnit 3 Test Item                                 nunit-test               [C#], F#, VB      Test/NUnit
xUnit Test Project                                xunit                    [C#], F#, VB      Test/xUnit
Razor Component                                   razorcomponent           [C#]              Web/ASP.NET
Razor Page                                        page                     [C#]              Web/ASP.NET
MVC ViewImports                                   viewimports              [C#]              Web/ASP.NET
MVC ViewStart                                     viewstart                [C#]              Web/ASP.NET
Blazor Server App                                 blazorserver             [C#]              Web/Blazor
Blazor WebAssembly App                            blazorwasm               [C#]              Web/Blazor/WebAssembly
ASP.NET Core Empty                                web                      [C#], F#          Web/Empty
ASP.NET Core Web App (Model-View-Controller)      mvc                      [C#], F#          Web/MVC
ASP.NET Core Web App                              webapp                   [C#]              Web/MVC/Razor Pages
ASP.NET Core with Angular                         angular                  [C#]              Web/MVC/SPA
ASP.NET Core with React.js                        react                    [C#]              Web/MVC/SPA
ASP.NET Core with React.js and Redux              reactredux               [C#]              Web/MVC/SPA
Razor Class Library                               razorclasslib            [C#]              Web/Razor/Library/Razor Class Library
ASP.NET Core Web API                              webapi                   [C#], F#          Web/WebAPI
ASP.NET Core gRPC Service                         grpc                     [C#]              Web/gRPC
dotnet gitignore file                             gitignore                                  Config
global.json file                                  globaljson                                 Config
NuGet Config                                      nugetconfig                                Config
Dotnet local tool manifest file                   tool-manifest                              Config
Web Config                                        webconfig                                  Config
Solution File                                     sln                                        Solution
Protocol Buffer File                              proto                                      Web/gRPC



創建網站專案
建立一空的 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




剛創建的 ASP.NET Core 空專案內容




白話簡單來講
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 <TStartup> 方法來指定
之後 Build 並 Run .NET Core App ,來轉為ASP.NET Core 應用程式。

CreateHostBuilder 呼叫 Host ClassCreateDefaultBuilder


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.


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.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則會看到 一樣的專案架構
而使用中斷點則運行順序如下
http://www.binaryintellect.net/articles/4fb59b82-a2a8-41ce-a55f-0a0a28cd6cbc.aspx

至於用vs code測試的由於預設無法下中斷點
需要額外裝套件








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

留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題