[ASP.Net Core] Day 1 - Note

ASP.Net Core - Day 1

Setup Environmen

  1. VS 2017 Community
  2. Dotnet COre 2.1
  3. SQL Server Express
  4. SQL Server Management Studio

建立 ASP.NET Core 專案

File => Project => Empty

ASP.NET Core 檔案結構

專案裡的檔案,主要以 Program.csStartup.cs 為主。

程式的進入點從 Program 開始,透過 WebHost,將 Startup 註冊進去。

$ ls
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        7/23/2018   5:57 PM                obj
d-----        7/23/2018   5:56 PM                Properties
d-----        7/23/2018   5:56 PM                wwwroot
-a----        7/23/2018   5:56 PM            630 Program.cs
-a----        7/23/2018   5:56 PM           1118 Startup.cs
-a----        7/23/2018   5:56 PM            310 testcore.csproj

主程式中,建立一個 WebHostBuilder,告訴 WebHost 要從哪一支程式開始 UseStartup

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Startup 裡, 透過 ConfigureServices ,註冊需要執行的服務。Configure 組態檔運行 ConfigureServices 所註冊進來的服務。

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, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

ConfigureServices

  1. 可選的,非必要,但是主要都是透過此方法註冊服務。
  2. WebHostConfigure 方法呼叫之前,用來設定應用程式的服務。
  3. 組態檔設定位置
/* appsettings.json */

Dependecy Injection

在 Asp.Net Core 裡面,它本身主要是一個 MVC 的框架,很多服務都透過 DI 的方式,注入到程式中運行。 另外,Asp.Net Core 裡面,註冊服務本身有三種方法。

  1. AddTransient - 每次注入時,都會重新產生一份實體。

  2. AddScoped - 每次請求時,產生一份實體。

  3. AddSingleton - 程式啟動時,產生一份實體,當系統運作時,也只會只有這一個實體存在。

/* AddTransient */
services.AddTransient<IXXXX, XXXX>();

/* AddScoped */
services.AddScoped<IXXXX, XXXX>();

/* AddSingleton */
services.AddSingleton<IXXXX, XXX>();
or
services.AddSingleton<IXXXX>(new XXX());

Asp.Net Core Process Pipeline

在整個流程的管線中,每個管線到下一個管線,都需要透過呼叫 next() 方法;如果在管線中,沒有呼叫 next() 則管線命令將結束,並於已返回。

    ----------------- Middlewaves -------------------------------
Request  => | -> ExceptionHandler -> Authorizer -> Router/Routes -> |
                  |                                                                                | |
                  |                                                                               V |
Response <= | <- HTTP 200 OK      <- HTTP 200 OK <- HTTP 200 OK  <- |
                          -------------------------------------------------------------

ExceptionHandler

主要專門處理例外部分

app.UseDeveloperExceptionPage();

Authorizer

主要處理授權認證部分

app.UseAuthentication();

Router/Routers

主要則是路由部分,將請求分配到哪個路由上。路由部分不是單單只能有一個,而是可以同時有多個路由。

app.UseMvc( routes => {
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute("myroute", "{controller=Home}/{action=Index}/{id?}");
});

另外,當 routes 變多時,我們的整個 Configure 方法會變得相當臃腫,可以透過呼叫靜態 ConfigureRoute 方法。

private static void ConfigureRoute(IRouteBuilder routes)
{
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute("myroute", "{controller=Home}/{action=Index}/{id?}");
}

...

app.UseMvc(ConfigureRoute);

...

Reference

  1. VS2017
  2. Dotnet Core 2.1
  3. SQL Server Express
  4. SQL Server Management Studio
  5. Dependency Injection
  6. ASP.NET Core 中的應用程式啟動

留言

這個網誌中的熱門文章

[Tools] GCOV & LCOV 初探

Quilt Patch 管理操作方法

[C#]C# Coding 規則