【问题标题】:Retrieve Application Version in ASP Net Core 2.0 MVC在 ASP Net Core 2.0 MVC 中检索应用程序版本
【发布时间】:2018-01-03 16:59:13
【问题描述】:

我即将在 Win10 上使用 .net core 2.0 和 vs2017 构建一个 mvc Web 应用程序。在编写“关于”页面时,我希望输入当前项目版本号(目前仍设置为 1.0.0)。我会认为这很简单!

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

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

但是,在我的情况下,这会返回“4.6.25814.01” - 这不是必需的。

谁能建议如何在代码中检索版本?

我假设我想要“包版本”,但承认我不清楚“包版本”、“程序集版本”和“程序集文件版本”之间的区别/如何使用。

【问题讨论】:

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


    【解决方案1】:

    当您调用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;
    

    如果你的项目的包版本设置如下,这将返回“6.6.7.0”:

    你很接近!

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

    【讨论】:

    • 非常感谢,西格。这完美地完成了这项工作。是否有任何关于项目/程序集可用的自定义属性的文档?例如,访问 Project Properties|Package 页面中的其他条目,这些条目在“About”页面上也可能有用?
    • 当然!在这里查看System.Reflection 中的类:docs.microsoft.com/en-us/dotnet/api/… 并尝试修改 AssemblyCompanyAttributeAssemblyCopyrightAttribute 等类。
    【解决方案2】:

    在 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 命名空间中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2017-12-29
      • 1970-01-01
      • 2011-05-02
      • 2020-03-29
      • 2022-01-26
      • 2010-10-31
      相关资源
      最近更新 更多