在ASP.NET MVC核心应用程序(RC2)中显示项目版本

如何从project.json显示应用程序版本? 我正在使用gulp-bump来自动增量版本,但我无法显示最新版本。 这是我正在尝试的:

 @(Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion) 

这不起作用,它显示“ 1.0.0 ”而不是来自project.json的实际值

我也试过这个,但看起来它不再适用于RC2:

 @inject Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment appEnv My version number is @(appEnv.ApplicationVersion) 

根据此声明 , IApplicationEnvironment不再存在。

您仍然可以使用以下方式静态访问ApplicationVersion

 Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion 

这个对我有用。 我的project.json看起来像这样:

 { "version": "1.0.0.2", // all the rest } 

在我的索引视图中,我在顶部有以下行:

 @Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion 

我在输出中正确得到1.0.0.2 。 当我更改该值并重新启动(构建)应用程序时,会在那里显示新版本。

由于Platform Abstractions与ASP.NET Core 1一起提供 ,并且已从ASP.NET Core 2及更高版本中删除,因此如果您使用的是版本2或更高版本,则必须替换此行:

 Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion 

与这一个:

 System.Reflection.Assembly.GetEntryAssembly().GetName().Version 

在上一个链接页面的“替换API用法”部分中指定。

我使用了一种不同的方法,如本回答所述,它给了我一个SemVer版本(1.0.0),它实际上是我的project.json而不是1.0.0.0,它是由接受的答案返回的。 所以代码是:

 var runtimeVersion = typeof(Startup) .GetTypeInfo() .Assembly .GetCustomAttribute() .InformationalVersion; 

它也会返回正确的后缀版本,例如“2.0.1-dev01”

这适用于.NET Core 2.0.5。

码:

 var assemblyVersion = System.Reflection.Assembly.GetEntryAssembly().GetCustomAttribute().InformationalVersion; Console.WriteLine(assemblyVersion); 

myproject.csproj

  1.0.0.1 alpha  

输出

 1.0.0.1-alpha