Getting the version of the executing assembly in ASP.NET Core 1.0 (previously ASP.NET 5)
Posted: (EET/GMT+2)
For many years, I've successfully used the following code in my ASP.NET web applications, including those written for MVC or WebForms, to retrieve the version of the executing assembly. Now that ASP.NET Core is soon here (in complete 1.0 version; the "Core 1.0" name was announced just last month), I wanted to share one breaking change I've noticed. I find it useful to be able to get the currently running application version for logging purposes.
Here's the routine I've been using:
public static string GetApplicationVersion()
{
Assembly thisDLL = Assembly.GetExecutingAssembly();
string version = thisDLL.GetName().Version.ToString();
return version;
}
When you have defined your application version in "AssemblyInfo.cs" (in ASP.NET 4.x applications), this routine will return the value of the AssemblyVersion attribute as a string.
But, this routine fails with ASP.NET Core, because the GetExecutingAssembly method is not available. If you try to use it, you will get the following error message:
Error CS0117: 'Assembly' does not contain a definition for 'GetExecutingAssembly'.
To get the above code to work, you need to slightly adjust the code:
public static string GetApplicationVersion()
{
Assembly thisDLL = typeof(SomeClassInsideYourProject).GetTypeInfo().Assembly;
string version = thisDLL.GetName().Version.ToString();
return version;
}
Above, you need to replace the "SomeClassInsideYourProject" name with something your project, such as the class containing the method itself. Notice how the new code uses the GetTypeInfo method instead.
Happy hacking with ASP.NET Core!