Blazor Server应用版本号相关问题:位置、读取及GitHub自动增量
Blazor Server 版本号管理方案(对标WinForms的AssemblyInfo机制)
Blazor Server完全支持类似WinForms的版本号管理、自动增量及展示机制,以下是具体问题的解答:
1. 版本号文件位置
- 现代.NET项目(含Blazor Server)默认不再使用单独的AssemblyInfo.cs文件,版本号直接定义在项目的
.csproj文件中。打开该文件,找到<Version>节点即可设置,示例:<Version>1.0.0</Version> - 若偏好传统AssemblyInfo模式,可在
.csproj中添加<GenerateAssemblyInfo>false</GenerateAssemblyInfo>,然后手动在项目的Properties目录下创建AssemblyInfo.cs,通过特性定义版本:[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
2. 编程方式读取版本号
方法一:从程序集直接读取
在Blazor组件中,通过反射获取当前程序集的版本信息:
@using System.Reflection @using System.Diagnostics @{ var assembly = Assembly.GetExecutingAssembly(); var assemblyVersion = assembly.GetName().Version?.ToString(); var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; } <p>程序集版本:@assemblyVersion</p> <p>文件版本:@fileVersion</p>
方法二:从配置文件读取
如果版本号被写入appsettings.json(可结合CI/CD自动注入),通过依赖注入读取:
@inject IConfiguration Config <p>应用版本:@Config["AppVersion"]</p>
3. GitHub Actions实现版本号自动增量
可以通过GitHub Actions快速实现发布时自动递增版本号,核心流程如下:
- 在项目的
.github/workflows目录下创建工作流文件(如publish-version.yml) - 编写工作流脚本,实现读取当前版本→递增版本→提交变更→构建发布的流程,示例简化版:
name: 发布并递增版本号 on: release: types: [published] # 触发条件:创建正式发布 jobs: build-and-version: runs-on: ubuntu-latest steps: - name: 拉取代码 uses: actions/checkout@v4 with: fetch-depth: 0 # 需要获取完整Git历史 - name: 递增版本号 uses: actions/github-script@v7 id: increment with: script: | const fs = require('fs'); const projectPath = './YourBlazorServerProject.csproj'; // 替换为你的项目文件路径 let content = fs.readFileSync(projectPath, 'utf8'); // 匹配<Version>x.x.x</Version>格式 const versionRegex = /<Version>(\d+)\.(\d+)\.(\d+)<\/Version>/; const match = content.match(versionRegex); if (match) { const major = parseInt(match[1]); const minor = parseInt(match[2]); const patch = parseInt(match[3]) + 1; const newVersion = `${major}.${minor}.${patch}`; // 替换版本号 content = content.replace(versionRegex, `<Version>${newVersion}</Version>`); fs.writeFileSync(projectPath, content); // 输出新版本号供后续步骤使用 core.setOutput('newVersion', newVersion); } - name: 提交版本变更 run: | git config --global user.name "GitHub Action Bot" git config --global user.email "action@github.com" git add YourBlazorServerProject.csproj git commit -m "自动递增版本至 ${{ steps.increment.outputs.newVersion }}" git push - name: 构建并发布 run: dotnet publish -c Release -o ./publish
提示:如果使用AssemblyInfo文件,只需修改脚本中的文件路径和版本匹配规则(比如匹配
AssemblyVersion特性)即可。
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

