Search code examples
asp.net-coreazure-devopsasp.net-core-webapiazure-pipelines-yaml

Access build number from Azure Devops to ASP.NET Core Web API


I have an ASP.NET Core Web API that is hosted on an Azure App service.

I am getting that build number inside YAML file like this:

variables:
  buildNumber: '$(Build.BuildNumber)' # Define a variable to hold the build number

steps:
- script: echo "Setting BUILD_NUMBER environment variable to $(buildNumber)"
  displayName: 'Set BUILD_NUMBER'

- script: echo "##vso[task.setvariable variable=BUILD_NUMBER]$(buildNumber)"
  displayName: 'Set BUILD_NUMBER environment variable'

I can see that build number in the log when it builds.

In my ASP.NET Core Web API, I have a method to read that value

 string buildNumber = Environment.GetEnvironmentVariable("BUILD_NUMBER") ?? "not available";

However, Environment.GetEnvironmentVariable("BUILD_NUMBER") is always null and BUILD_NUMBER is not found.

Question is, how do I associate BUILD_NUMBER inside the .yaml file with the API method, so that this build number can be retrieved in the API?

Am I missing a step here? Thanks.


Solution

  • The cause of the issue could be that setting the environment variable would only work if you started your console application via dotnet run.

    Refer to this doc: Use multiple environments in ASP.NET Core

    When the ASPNETCORE_ENVIRONMENT environment variable is set globally, it takes effect for dotnet run in any command window opened after the value is set.

    You can run the dotnet run command in Azure Pipeline and check if the environment variable can pass to application successfully.

    Here is my test sample:

    Add the code to .cs file:

    string buildNumber = Environment.GetEnvironmentVariable("BUILD_NUMBER");
    Console.WriteLine(buildNumber);
    

    Run dotnet Run in Azure Pipeline:

    variables:
      buildNumber: '$(Build.BuildNumber)' # Define a variable to hold the build number
    
    steps:
    - script: echo "Setting BUILD_NUMBER environment variable to $(buildNumber)"
      displayName: 'Set BUILD_NUMBER'
    
    - script: echo "##vso[task.setvariable variable=BUILD_NUMBER]$(buildNumber)"
      displayName: 'Set BUILD_NUMBER environment variable'
    
    - task: DotNetCoreCLI@2
      inputs:
        command: 'run'
        projects: 'SampleWebApiAspNetCore/SampleWebApiAspNetCore.csproj'
    

    enter image description here

    If you want to let it work when deploying to Azure Web App, you can set the variable to appsettings of Azure Web App in the Azure App Service Deploy task.

    For example:

    - task: AzureRmWebAppDeployment@4
      displayName: 'Azure App Service Deploy: AA'
      inputs:
        azureSubscription: xx
        WebAppName: appname
        AppSettings: '-BUILD_NUMBER $(BUILD_NUMBER)'
    

    For more detailed info, you can refer to this doc: Azure App Service Environment