Vue 和 ASP.NET Core Web API 專案整合(一)
Vue 和 ASP.NET Core Web API 專案整合(一)
Vue 是一個流行的 JavaScript 框架,它可以協助開發者快速開發單頁應用程式。而 ASP.NET Core Web API 則是一個開發 Web API 的框架。在開發 Web 應用程式時,Vue 和 ASP.NET Core Web API 的整合十分常見。
網路上,已有不少大神,製作整合範本,下載即可使用,只是這類專案需要依賴維護,版本也不一定是自己想要的,所以寫了幾篇常見的架構,並且均以內建的專案為主,下面將介紹 Vue 和 ASP.NET Core Web API 專案整合的步驟。
常見的專案架構大概可以分幾種,各自架構都有不同的優缺點
- WebApi 與 Vue 位於同一個專案(本篇介紹)
- WebApi 與 Vue 各自不同專案,但同一個方案底下
專案架構
環境介紹
- .NET Core 6
Program.cs
,也會有不同的設定- Vite
步驟一:創建 ASP.NET Core Web API 專案
首先,需要創建一個 ASP.NET Core Web API 專案。這邊我習慣從空白方案開始,比較容易命名不同的專案用途。
加入 ASP.NET Core Web API
步驟二:創建 Vue 專案
接下來,需要創建一個 Vue 專案。
-
在 ASP.NET Core Web API 專案中,新增一個 ClientApp 資料夾,用來放 Vue 專案。
-
在 ClientApp 資料夾內,執行
Vite
指令,創建 Vue 專案。1
npm create vite@latest my-vue-app -- --template vue
-
將創建出來Vue專案內容,搬到上一層(ClientApp資料夾中)。
-
刪掉空白 my-vue-app 資料夾
步驟三:測試執行
-
先查看 ASP.NET Core Web API 專案中
launchSettings.json
內的applicationUrl
的 IP。 -
在 Vue 專案中
vite.config.js
,設置讀取 API 的代理1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { host: true, port: 5002, proxy: { '/api': { target: 'https://localhost:7032', changeOrigin: true, secure: false, }, }, }, })
-
執行
npm i
安裝執行 vue 等必要依賴 -
測試 API 是否正常運行
1 2 3 4 5 6 7
fetch("/api/weatherForecast") .then(function (response) { return response.json(); }) .then(function (myJson) { console.log(myJson); });
步驟三:發佈與整合 ASP.NET Core Web API 和 Vue
確認可正常開發後,接著便是發佈與整合了,Vue 專案預設會將編譯後的檔案輸出到 dist
資料夾中。而 ASP.NET Core 則預設使用 wwwroot
作為靜態文件的入口,所以我們希望將編譯出來的資料放在 wwwroot
資料夾。
-
如果在 ASP.NET Core Web API 專案中,沒有
wwwroot
,則手動建立一個。 -
在 ASP.NET Core Web API 專案中,打開
Program.cs
文件,添加使用UseDefaultFiles
、UseStaticFiles
,及MapFallbackToFile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } else { app.UseDefaultFiles(); // Add app.UseStaticFiles(); // Add } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapFallbackToFile("index.html"); // Add app.Run();
如果環境是 .NET Core 3 以下,要額外安裝 AspNetCore.SpaServices.Extensions,並且
Program
,應改為1 2 3 4 5 6 7 8 9 10
builder.Services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; }); app.UseSpaStaticFiles(); app.UseSpa(spa => { spa.Options.DefaultPage = "/index.html"; });
-
在 Vue 專案中
vite.config.js
,編譯匯出位置1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
export default defineConfig({ plugins: [vue()], server: { host: true, port: 5002, proxy: { '/api': { target: 'https://localhost:7032', changeOrigin: true, secure: false, }, }, }, build: { outDir: '../wwwroot' } })
-
執行
npm run build
,再查看wwwroot
是否有編譯過的檔案 -
最後,可以設置建置前事件,在重建、新建時,可以先去跑
npm run build
。這部分依照個人習慣
總結
各架構在內容設置上,都是大同小異的,較大差異在於如何匯出編譯後的靜態檔案至ASP.NET Core Web Api,而 WebApi 與 Vue 位於同一個專案是最容易設置的,很適合單人開發,較大缺點是前後端同處於一個專案下,關注點與職責分離不夠明確,如果是兩人以上團隊,每人都需要拿到這份包含前後端的專案。