Introduction
I frequently need to set a (this is a
Checking that the version reported from HTTP services (web apps ,APIs) is correct is a crucial part of my CD pipelines and is one of the (smoke) tests I use to determine if the deployment succeeded.
In this post Ill show you how to stamp a semver version number on a .NET assembly - i.e. an .exe or .dll compiled using a .NET compiler - during build, then read it at run time.
So many version numbers
As Andrew Locks (free) or
In the screenshot above, Product version is the caption for InformationalVersion whereas File version is the caption for FIleVersion.
Of the four types of version numbers described above, only the first three apply to any assembly (i.e. whether or not the assembly is part of a Nuget package).
Of those three, AssemblyVersion alsways adds a 0 in the fourth place if you try to set a semver version which only has three numbers (plus an optional prerelease suffix). For example if you try to set a semver version of 1.0.2-beta during build and then read the AssemblyVersion value at run time in the assembly, it would be 1.0.2.0.
FileVersion does the same, as shown in the screenshot above.
InformationalVersion is the only version number which would get set exactly to the server version we set during build (as screenshot above shows).
Therefore, InformationalVersion is the version that should be read at run time.
Set a SemVer version number
In a
<PropertyGroup>element in the projectscsprojfile, add element<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>:Pass the version number as value of
Versionparameter ofdotnet builde.g.:
Reading an assemblys SemVer version at run time
Code that reads InfromationalVersion at run time is as follows:
string? version = Assembly.GetEntryAssembly()?. GetCustomAttribute<AssemblyInformationalVersionAttribute>()?. InformationalVersion;
In my minimal APIs, to add a /version endpoint as I showed in Inroduction section above, I place the above snippet in Program.cs, before builder.Build() is called, then add the following snippet immediately after:
//this object of an anonymous type will //be serialised as JSON in response body//when returned by a handlervar objVersion = new { Version = version ?? "" };//OTHER CODE//var app = builder.Build()
After builder.Build() is called, I create the handler for /version endpoint:
app.MapGet("/version", () => objVersion);
Now when I run the API project and call the /version endpoint, I get the version number back in a JSON object in HTTP response body:
{ "version": "1.0.2-beta"}
SOCIAL SHARE CARD GENERATOR