You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Azure Functions配置版本并在运行时查询代码版本?

解决Azure Function获取代码版本的问题

我之前在Azure Functions里也碰到过完全一样的困扰,毕竟它的运行模型和普通.NET应用差异不小。除了手动配置应用设置外,这几个方案亲测有效:

1. 改用AssemblyInformationalVersion获取版本

Azure Functions在打包发布时,有时候会自动覆盖程序集的AssemblyVersion(这就是你拿到1.0的原因),但AssemblyInformationalVersion通常会被保留,是更可靠的版本标识。

设置方法

直接在你的.csproj项目文件里添加或修改以下配置:

<PropertyGroup>
  <!-- 直接指定自定义版本号 -->
  <AssemblyInformationalVersion>2.1.0-beta</AssemblyInformationalVersion>
  <!-- 或者用.NET的Version属性,它会同时设置AssemblyVersion和AssemblyInformationalVersion,即使AssemblyVersion被覆盖,InformationalVersion依然有效 -->
  <!-- <Version>2.1.0-beta</Version> -->
</PropertyGroup>

获取代码

替换你原来的代码,改用下面的方式获取:

using System.Reflection;

var informationalVersion = Assembly.GetExecutingAssembly()
    .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
    .InformationalVersion;

2. 嵌入版本文件到部署包

你可以在构建/发布流程中生成一个包含版本信息的文件,然后在Function代码里读取它:

步骤

  • 在构建脚本(比如Azure DevOps Pipeline、GitHub Actions)中,添加步骤生成version.txt文件,内容为你的版本号(可从Git标签、构建编号自动获取):
    echo "2.1.0-beta" > $(Build.ArtifactStagingDirectory)/version.txt
    
  • 确保这个文件被包含在部署包中,在.csproj里添加:
    <None Include="version.txt" CopyToOutputDirectory="PreserveNewest" />
    
  • 在Function代码中读取:
    var versionPath = Path.Combine(Environment.CurrentDirectory, "version.txt");
    var version = File.ReadAllText(versionPath).Trim();
    

3. 用Git提交哈希作为版本标识

如果你的代码托管在Git仓库,用提交哈希作为版本标识既可靠又不需要手动维护版本号,还能直接关联到具体的代码变更:

设置方法

在.csproj里添加配置,将Git哈希注入到AssemblyInformationalVersion:

<PropertyGroup>
  <AssemblyInformationalVersion>$([System.DateTime]::Now.ToString("yyyy.MM.dd"))-$(GitCommitHash)</AssemblyInformationalVersion>
</PropertyGroup>

然后在构建时,通过命令行获取Git短哈希并传给MSBuild:

dotnet build /p:GitCommitHash=$(git rev-parse --short HEAD)

获取代码

和方案1一样,通过AssemblyInformationalVersionAttribute获取即可,结果会类似2024.05.20-a1b2c3d,包含日期和提交哈希,辨识度拉满。


内容的提问来源于stack exchange,提问作者ChrisHDog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:06:22