This commit is contained in:
2026-07-24 12:47:12 +08:00 Unverified
parent 67905dfa16
commit 6c3021ea8d
6 changed files with 125 additions and 13 deletions
+2
View File
@@ -2,6 +2,7 @@
**/obj/ **/obj/
**/node_modules/ **/node_modules/
**/dist/ **/dist/
.artifacts/
.vs/ .vs/
.vscode/ .vscode/
*.user *.user
@@ -10,6 +11,7 @@
*.sqlite-shm *.sqlite-shm
*.sqlite-wal *.sqlite-wal
src/Jiaowu.Api/data/ src/Jiaowu.Api/data/
src/Jiaowu.Api/wwwroot/
.env .env
.env.* .env.*
!.env.example !.env.example
+19 -5
View File
@@ -2,7 +2,7 @@
面向普通高校的教务管理系统。后端使用 ASP.NET Core 10、EF Core 10,前端使用 Vue 3、TypeScript 和 Element Plus。 面向普通高校的教务管理系统。后端使用 ASP.NET Core 10、EF Core 10,前端使用 Vue 3、TypeScript 和 Element Plus。
## 本地开发 ## 本地开发:热更新模式
本地开发固定使用 SQLite。首次启动会自动创建 `src/Jiaowu.Api/data/jiaowu-dev.sqlite` 并写入演示组织数据。 本地开发固定使用 SQLite。首次启动会自动创建 `src/Jiaowu.Api/data/jiaowu-dev.sqlite` 并写入演示组织数据。
@@ -20,18 +20,32 @@ npm run dev
访问 `http://localhost:5173`,开发账号为 `admin`,密码为 `Admin@123456` 访问 `http://localhost:5173`,开发账号为 `admin`,密码为 `Admin@123456`
## 本地开发:单服务模式
不需要前端热更新时,可以先把 Vue 编译进 API 的 `wwwroot`
```powershell
npm --prefix web run build
dotnet run --project src/Jiaowu.Api
```
访问 `http://localhost:5255``/api` 和静态页面由同一个 ASP.NET Core 服务提供,`/base-data` 等前端路由刷新时也会回退到 `index.html`
## MySQL 部署 ## MySQL 部署
非 Development 环境只允许使用 MySQL。连接串和 JWT 密钥应通过环境变量或安全配置中心提供 非 Development 环境只允许使用 MySQL。`dotnet publish` 会自动执行 `npm ci``npm run build`,并将 Vue 静态文件放入发布目录的 `wwwroot`
```powershell ```powershell
$env:ASPNETCORE_ENVIRONMENT = 'Production' $env:ASPNETCORE_ENVIRONMENT = 'Production'
$env:Database__Provider = 'MySql' $env:Database__Provider = 'MySql'
$env:ConnectionStrings__MySql = 'Server=127.0.0.1;Port=3306;Database=jiaowu;User=YOUR_USER;Password=YOUR_PASSWORD;' $env:ConnectionStrings__MySql = 'Server=127.0.0.1;Port=3306;Database=jiaowu;User=YOUR_USER;Password=YOUR_PASSWORD;'
$env:Jwt__Key = '至少32字节的随机生产密钥' $env:Jwt__Key = '至少32字节的随机生产密钥'
dotnet run --project src/Jiaowu.Api dotnet publish src/Jiaowu.Api -c Release -o .artifacts/publish
.artifacts/publish/Jiaowu.Api.exe
``` ```
如需在特殊流水线中跳过自动前端构建,可传入 `-p:BuildFrontendOnPublish=false`
生产环境不会创建默认管理员。首次部署前可以临时配置 `SeedAdmin__UserName``SeedAdmin__Password``SeedAdmin__DisplayName`,账号创建后移除这些配置。 生产环境不会创建默认管理员。首次部署前可以临时配置 `SeedAdmin__UserName``SeedAdmin__Password``SeedAdmin__DisplayName`,账号创建后移除这些配置。
生产数据库使用 MySQL 专用 EF Core 迁移。部署前先恢复仓库工具并检查迁移: 生产数据库使用 MySQL 专用 EF Core 迁移。部署前先恢复仓库工具并检查迁移:
@@ -47,6 +61,6 @@ dotnet ef migrations list --project src/Jiaowu.Api --startup-project src/Jiaowu.
```powershell ```powershell
dotnet test Jiaowu.slnx dotnet test Jiaowu.slnx
Set-Location web npm --prefix web run build
npm run build pwsh.exe -NoLogo -NoProfile -NonInteractive -File scripts/smoke-test.ps1
``` ```
+29 -3
View File
@@ -1,15 +1,30 @@
param(
[string] $ApiExecutablePath,
[string] $ApiContentRoot
)
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$workspaceRoot = Split-Path -Parent $PSScriptRoot $workspaceRoot = Split-Path -Parent $PSScriptRoot
$apiProjectDirectory = Join-Path $workspaceRoot 'src/Jiaowu.Api' $apiExecutable = if ([string]::IsNullOrWhiteSpace($ApiExecutablePath)) {
$apiExecutable = Join-Path $workspaceRoot 'src/Jiaowu.Api/bin/Debug/net10.0/Jiaowu.Api.exe' Join-Path $workspaceRoot 'src/Jiaowu.Api/bin/Debug/net10.0/Jiaowu.Api.exe'
}
else {
[System.IO.Path]::GetFullPath($ApiExecutablePath, $workspaceRoot)
}
$apiWorkingDirectory = if ([string]::IsNullOrWhiteSpace($ApiContentRoot)) {
Join-Path $workspaceRoot 'src/Jiaowu.Api'
}
else {
[System.IO.Path]::GetFullPath($ApiContentRoot, $workspaceRoot)
}
$stdoutPath = Join-Path $env:TEMP 'jiaowu-api-smoke.out.log' $stdoutPath = Join-Path $env:TEMP 'jiaowu-api-smoke.out.log'
$stderrPath = Join-Path $env:TEMP 'jiaowu-api-smoke.err.log' $stderrPath = Join-Path $env:TEMP 'jiaowu-api-smoke.err.log'
$env:ASPNETCORE_ENVIRONMENT = 'Development' $env:ASPNETCORE_ENVIRONMENT = 'Development'
$env:ASPNETCORE_URLS = 'http://localhost:5255' $env:ASPNETCORE_URLS = 'http://localhost:5255'
$startParameters = @{ $startParameters = @{
FilePath = $apiExecutable FilePath = $apiExecutable
WorkingDirectory = $apiProjectDirectory WorkingDirectory = $apiWorkingDirectory
WindowStyle = 'Hidden' WindowStyle = 'Hidden'
RedirectStandardOutput = $stdoutPath RedirectStandardOutput = $stdoutPath
RedirectStandardError = $stderrPath RedirectStandardError = $stderrPath
@@ -51,6 +66,14 @@ try {
$headers = @{ Authorization = "Bearer $($login.token)" } $headers = @{ Authorization = "Bearer $($login.token)" }
$dashboard = Invoke-RestMethod -Uri 'http://localhost:5255/api/dashboard' -Headers $headers $dashboard = Invoke-RestMethod -Uri 'http://localhost:5255/api/dashboard' -Headers $headers
$campuses = Invoke-RestMethod -Uri 'http://localhost:5255/api/base-data/campuses' -Headers $headers $campuses = Invoke-RestMethod -Uri 'http://localhost:5255/api/base-data/campuses' -Headers $headers
$frontend = Invoke-WebRequest -Uri 'http://localhost:5255/' -TimeoutSec 5
$spaFallback = Invoke-WebRequest -Uri 'http://localhost:5255/base-data' -TimeoutSec 5
$unknownApiParameters = @{
Uri = 'http://localhost:5255/api/does-not-exist'
SkipHttpErrorCheck = $true
TimeoutSec = 5
}
$unknownApi = Invoke-WebRequest @unknownApiParameters
[pscustomobject]@{ [pscustomobject]@{
Health = $health.status Health = $health.status
@@ -58,6 +81,9 @@ try {
User = $login.user.displayName User = $login.user.displayName
Term = $dashboard.currentTerm.name Term = $dashboard.currentTerm.name
Campuses = @($campuses).Count Campuses = @($campuses).Count
StaticIndex = $frontend.Content.Contains('明序教务管理系统')
SpaFallback = $spaFallback.StatusCode
ApiNotFound = $unknownApi.StatusCode
} | Format-List } | Format-List
} }
finally { finally {
+24
View File
@@ -4,8 +4,14 @@
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<SpaRoot>$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/../../web'))</SpaRoot>
<BuildFrontendOnPublish Condition="'$(BuildFrontendOnPublish)' == ''">true</BuildFrontendOnPublish>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Content Remove="wwwroot\**\*" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.10" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.10" />
@@ -19,4 +25,22 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup> </ItemGroup>
<Target
Name="BuildVueFrontendForPublish"
AfterTargets="ComputeFilesToPublish"
Condition="'$(BuildFrontendOnPublish)' == 'true' and Exists('$(SpaRoot)/package.json')">
<Message Importance="high" Text="Building Vue frontend for ASP.NET Core publish..." />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm ci" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />
<ItemGroup>
<FrontendFiles Include="$(MSBuildProjectDirectory)\wwwroot\**\*" />
<ResolvedFileToPublish Include="@(FrontendFiles->'%(FullPath)')">
<RelativePath>wwwroot\%(RecursiveDir)%(Filename)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
</Project> </Project>
+42
View File
@@ -182,6 +182,25 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI(); app.UseSwaggerUI();
} }
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
if (context.Context.Request.Path.StartsWithSegments("/assets"))
{
context.Context.Response.Headers.CacheControl =
"public,max-age=31536000,immutable";
}
else if (string.Equals(
Path.GetExtension(context.File.Name),
".html",
StringComparison.OrdinalIgnoreCase))
{
context.Context.Response.Headers.CacheControl = "no-cache,no-store";
}
}
});
app.UseCors("Web"); app.UseCors("Web");
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
@@ -194,6 +213,29 @@ app.MapGet("/health", () => Results.Ok(new
Environment = app.Environment.EnvironmentName, Environment = app.Environment.EnvironmentName,
Time = DateTimeOffset.UtcNow Time = DateTimeOffset.UtcNow
})).AllowAnonymous(); })).AllowAnonymous();
app.MapFallback(async context =>
{
if (context.Request.Path.StartsWithSegments("/api") ||
context.Request.Path.StartsWithSegments("/health") ||
context.Request.Path.StartsWithSegments("/swagger"))
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
var webRoot = app.Environment.WebRootPath
?? Path.Combine(app.Environment.ContentRootPath, "wwwroot");
var indexPath = Path.Combine(webRoot, "index.html");
if (!File.Exists(indexPath))
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
context.Response.Headers.CacheControl = "no-cache,no-store";
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.SendFileAsync(indexPath);
});
using (var scope = app.Services.CreateScope()) using (var scope = app.Services.CreateScope())
{ {
+4
View File
@@ -17,6 +17,10 @@ export default defineConfig({
dts: 'src/components.d.ts', dts: 'src/components.d.ts',
}), }),
], ],
build: {
outDir: '../src/Jiaowu.Api/wwwroot',
emptyOutDir: true,
},
server: { server: {
port: 5173, port: 5173,
proxy: { proxy: {