ASP.NET Core Web API 整合 Angular 至同站台

以下是我覺得將 ASP.NET Core Web API 整合 Angular 至同站台比較簡單的方式

事前準備

  • 建立 Angular 專案 (版本 Angular 13)

    1
    2
    ng new demo1 --routing --style=css
    cd demo1
    
    • 建立 demo component

      1
      ng generate component demo
      
    • app.module.ts 匯入 HttpClientModule

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      @NgModule({
        declarations: [
          AppComponent,
          DemoComponent,
        ],
        imports: [
          BrowserModule,
          HttpClientModule, // 匯入 HttpClientModule
          AppRoutingModule
        ],
        providers: []
        bootstrap: [ AppComponent ]
      })
      export class AppModule { }
      
    • demo.component.ts 注入 HttpClient

      1
      constructor(private http: HttpClient) { }
      
    • demo.component.ts 呼叫 ASP.NET Core Web API 專案的 API

      1
      2
      3
      4
      ngOnInit(): void {
        this.http.get('/weatherForecast')
          .subscribe(data => console.log(data))
      }
      
    • app-routing.module.ts 加入 demo 路由

      1
      2
      3
      4
      5
      6
      const routes: Routes = [
        {
          path: 'demo',
          component: DemoComponent
        }
      ];
      
  • 建置 Angular 專案

    1
    ng build --prod
    

整合至 ASP.NET Core Web API 專案

  • 建立 ASP.NET Core Web API 專案 (版本 .NET 6)

    1
    2
    dotnet new webapi -n Demo
    cd Demo
    
  • 建立 wwwroot 資料夾

    1
    mkdir wwwroot
    
  • 將 Angular 建置出的 dist 裡的 demo 資料夾的內容複製至 wwwroot

  • 修改 Program.cs

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
      
    app.UseHttpsRedirection();
       
    // 讀取靜態檔案
    app.UseDefaultFiles();
    app.UseStaticFiles();
    
    app.UseAuthorization();
    
    app.MapControllers();
    // 若找不到 API,則導到 /index.html
    app.MapFallbackToFile("/index.html");
    
    app.Run();
    
  • 執行程式並切到 /demo 路由,在 Console 就能看到順利呼叫 API

    1
    dotnet run
    

    image