.NET Core App - How to get build number at runtime

2020-03-17 04:29发布

I've got a .NET Core MVC app which is built using TFS online, and published to Azure using the Release management stuff in TFS online. All very nice.

What I'd like to do is have my app display the build number somewhere. Doesn't matter where...but for example in a WebAPI endpoint like /api/buildversion.

Can anyone help with how I can get the TFS build number at runtime? When the app is packaged/published is there any file which contains the build number that I can access from the application?

3条回答
forever°为你锁心
2楼-- · 2020-03-17 05:02

There is an easier way than adding more plugins and libraries. If you are using the web/app deploy method, expand the File Transforms & Variables enter image description here

Assuming you want to update say a build number value in your appsettings.json

enter image description here

Then just update the variables setting in your release definition of VSTS enter image description here

Super easy. This is more or less the same steps in Octopus IIRC.

查看更多
Juvenile、少年°
3楼-- · 2020-03-17 05:12

The simple way is that you can store the build number in a file (e.g. appsettings.json), then get this data in app code.

Appsettings.json sample code:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-ab933d83-8f4b-4024-9f3c-1aef5339a8f3;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
  "CodeVersion": {
    "Num": "#{MyBuildNumber}#"
  }
}
  1. Install Replace Tokens extension
  2. Edit your build definition
  3. Click Variables tab and add a variable. (Name: MyBuildNumber, Value:$(Build.BuildNumber))
  4. Add Replace Tokens build step before build step

enter image description here

查看更多
你好瞎i
4楼-- · 2020-03-17 05:13

You need to save the Build Number in your application at compile time.

You can access the build number with $Build.BuildNumber or $Env:BUILD_BUILDNUMBER depending on your environment. I usually write it as a variable into my ApplicationInfo.* with both the version and build number.

查看更多
登录 后发表回答