如何检索产品版本?

时间:2016-03-09 22:07:03

标签: c# asp.net-core versioning asp.net-core-mvc

有没有办法检索ASP.NET 5 Web应用程序的产品版本?

这就是我project.json中的内容:

"version": "4.0.0-alpha1"

如何从应用程序中检索此内容?我曾经能够在较旧的ASP.NET版本上执行此操作:

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

然而,现在它只是给了我0.0.0.0。有什么想法吗?

2 个答案:

答案 0 :(得分:6)

在project.json文件中添加对System.Reflection的引用(如果您还没有)。

"dependencies": {
    "System.Reflection": "4.1.0-beta-23516" // Current version at time of posting
}

然后,您可以从AssemblyInformationalVersionAttribute InformationalVersion属性中获取值。

private static string GetRuntimeVersion() =>
        typeof(SomeClassInYourAssembly)
            .GetTypeInfo()
            .Assembly
            .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
            .InformationalVersion;

答案 1 :(得分:2)

在需要版本的任何位置注入IApplicationEnvironment。例如,在Startup类的Configure方法中:

       public void Configure(IApplicationBuilder app, 
        IApplicationEnvironment applicationEnvironment)
    {
        app.UseIISPlatformHandler();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(applicationEnvironment.ApplicationVersion);
        });
    }

来源:“启动时可用的服务”http://docs.asp.net/en/latest/fundamentals/startup.html