Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Application Version in ASP Net Core 2.0 MVC

I am finishing off building an mvc web application using .net core 2.0 with vs2017 on Win10.In writing an 'About' page I looked to put in the current project version number (at present still set at 1.0.0). I would have thought that pretty straightforward!

The only reference I could find suggested:

AppVersion = typeof(RuntimeEnvironment).GetTypeInfo ().Assembly
    .GetCustomAttribute<AssemblyFileVersionAttribute> ().Version;

However, this returns, in my case, '4.6.25814.01' - not what is required.

Can anyone suggest how to retrieve the version in code, please?

I assume that I want the 'Package Version' but admit I am not clear on the distinction between/how one would use 'Package Version', 'Assembly Version' and 'Assembly File Version'.

like image 648
David Avatar asked Jan 03 '18 16:01

David


2 Answers

When you call typeof(RuntimeEnvironment).Assembly, you're querying the containing assembly of that type. In this case this would be System.Runtime.InteropServices.dll or Microsoft.Dotnet.PlatformAbstractions.dll, depending on the namespace you've imported.

To get the information of your own assembly, you could simply replace RuntimeEnvironment with one of your own types, for example

var appVersion = typeof(Program).Assembly
    .GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

or even

var appVersion = typeof(HomeController).Assembly
    .GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

This would return "6.6.7.0" if the Package version if your project is set as follows:

enter image description here

You were close!

Here you can find more information on reflection for .NET in general, but it should work fine for .NET Core.

like image 158
Sigge Avatar answered Nov 09 '22 13:11

Sigge


Tried on version 2.0

using System.Reflection;

var appVersion = string.Empty;
var customAttribute = typeof(Program).Assembly.GetCustomAttributes(false).SingleOrDefault(o => o.GetType() == typeof(AssemblyFileVersionAttribute));
if (null != customAttribute)
{
    if (customAttribute is AssemblyFileVersionAttribute)
    {
        var fileVersionAttribute = customAttribute as AssemblyFileVersionAttribute;
        appVersion = fileVersionAttribute.Version;
    }
}

AssemblyFileVersionAttribute type is in System.Reflection namespace.

like image 1
pmdot Avatar answered Nov 09 '22 12:11

pmdot