在ASP Net Core 2.0 MVC中检索应用程序版本

时间:2018-01-03 16:59:14

标签: asp.net-core-mvc asp.net-core-2.0

我正在Win10上使用.net core 2.0和vs2017构建一个mvc Web应用程序。在写一个'关于'页面我看起来放入当前项目版本号(目前仍然设置为1.0.0)。我原以为这非常简单!

我能找到的唯一参考建议:

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

然而,在我的情况下,这将返回&#39; 4.6.25814.01&#39; - 不是所需要的。

有人可以建议如何在代码中检索版本吗?

我认为我想要&#39;包版本&#39;但我承认我不清楚人们如何使用&#39;包版本&#39;,#39;汇编版本&#39;和&#39;汇编文件版本&#39;。

2 个答案:

答案 0 :(得分:10)

当您致电typeof(RuntimeEnvironment).Assembly时,您正在查询该类型的包含程序集。在这种情况下,这将是System.Runtime.InteropServices.dllMicrosoft.Dotnet.PlatformAbstractions.dll,具体取决于您导入的命名空间。

要获取您自己的程序集的信息,您只需将RuntimeEnvironment替换为您自己的类型,例如

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

甚至

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

这将返回&#34; 6.6.7.0&#34;如果您的项目设置如下的Package版本:

enter image description here

你很亲密!

Here您可以找到有关.NET反射的更多信息,但它应该适用于.NET Core。

答案 1 :(得分:1)

试用版本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类型位于System.Reflection命名空间中。