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

在.NET Core Azure DevOps流水线中设置环境变量供Web App读取使用

实现方案

1. 操作位置选择

两种方案都合法,根据你的发布流程选择即可:

  • 优先选择发布流水线配置:适合单次构建、多环境发布的场景,不需要修改构建逻辑,直接复用构建产物发布到不同环境,变量取值用Release.Artifacts.{alias}.SourceVersion即可
  • 也可以选择构建流水线配置:适合需要将Commit ID固化到构建产物的场景,变量取值用Build.SourceVersion即可

2. 环境变量配置方法

2.1 发布流水线配置(推荐)

如果你用Azure DevOps内置的「Azure App Service部署」任务,直接在任务的应用和配置设置输入框中填入以下键值对即可:

CommitId=$(Release.Artifacts.{你的制品别名}.SourceVersion)

注意:{你的制品别名}需要替换为发布流水线「制品」板块中你配置的构建制品别名,可直接在发布流水线配置页的制品卡片上查看。

如果需要用PowerShell脚本实现,添加一个「Azure PowerShell」任务,执行以下脚本即可:

az webapp config appsettings set --name <Web应用名称> --resource-group <资源组名称> --settings CommitId=$(Release.Artifacts.{你的制品别名}.SourceVersion)

2.2 构建流水线配置

在构建任务前添加一个PowerShell任务,执行以下脚本将Commit ID写入配置文件:

$appSettingsPath = "$(Build.SourcesDirectory)/appsettings.json"
$appSettings = Get-Content $appSettingsPath | ConvertFrom-Json
$appSettings | Add-Member -MemberType NoteProperty -Name "CommitId" -Value "$(Build.SourceVersion)" -Force
$appSettings | ConvertTo-Json -Depth 10 | Set-Content $appSettingsPath

3. 代码层面读取与响应头附加

.NET Core 3.1默认会加载环境变量、appsettings.json中的配置到IConfiguration对象中,直接读取即可,示例代码如下:

3.1 自定义中间件实现响应头注入

// 自定义中间件
public class CommitIdHeaderMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _commitId;

    public CommitIdHeaderMiddleware(RequestDelegate next, IConfiguration config)
    {
        _next = next;
        // 读取CommitId,不存在则返回unknown
        _commitId = config["CommitId"] ?? "unknown";
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 附加响应头
        context.Response.Headers["X-Git-Commit-Id"] = _commitId;
        await _next(context);
    }
}

3.2 注册中间件

在Startup.cs的Configure方法中,路由配置前注册中间件即可:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其他中间件...
    app.UseMiddleware<CommitIdHeaderMiddleware>();
    app.UseRouting();
    // 其他配置...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:15:04