.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


<<:  Day–3 Excel之快速移动栏列之术

>>:  Label元件字串太长时的解法

IT 铁人赛 k8s 入门30天 -- day13 Deploying Stateful Apps with StatefulSet

前言 今天主要会介绍 StatefulSet 以及比较其与 Deployment 的不同 State...

Day29. 范例:运输系统 (抽象工厂模式)

本文同步更新於blog 前情提要:铁路运输系统,参考范例:运输系统(工厂方法模式) <?p...

Day04 - 事件、状态转移

我们必须记忆一个主体的状态,以便系统後续进行判断、操作或其他使用,为此我们也在 Day 03 厘清「...

Day19 - 中场休息时间 - 怎麽样用Canvas精准的写出一个『字』 - 成为Canvas Ninja ~ 理解2D渲染的精髓

呃,首先呢~ 敝人小弟在下我今天仔细的思考了一下,决定这次还是再来一篇『中场休息』科普文,等到明天再...

从零开始的8-bit迷宫探险【Level 11】在 iPhone 里盖座迷宫,就。很。墙

黑森林的样貌正如其名,不管白天或黑夜,一但走进了森林里就伸手不见五指... 长老说:「少年,你确定...