c# - 使用程序集中的 Web 应用程序版本号 (ASP.NET/C#)

标签 c# .net asp.net reflection assemblies

如何在引用的程序集中获取调用 Web 应用程序的版本号?

我试过使用 System.Reflection.Assembly.GetCallingAssembly().GetName() 但它只给我动态编译的程序集(返回版本号 0.0.0.0)。

更新:在我的例子中,我需要一个不需要引用回 Web 应用程序程序集中的类的解决方案。 Jason 在下面的回答(标记为已接受)满足此要求 - 此处提交的许多其他回答没有。

最佳答案

这是我使用的一些代码,支持从 Web 或非 Web 应用程序获取应用程序的“主”程序集,然后您可以使用 GetName().Version 获取版本。

它首先尝试对非 Web 应用程序使用 GetEntryAssembly()。这在 ASP.NET 下返回 null。 然后它会查看 HttpContext.Current 以确定这是否是一个 Web 应用程序。然后它使用当前 HttpHandler 的类型 - 但如果调用是从 ASPX 页面进行的,则此类型的程序集可能是生成的 ASP.NET 程序集,因此它遍历 HttpHandler 的 BaseType 链,直到找到不在其中的类型ASP.NET 用于其生成类型(“ASP”)的命名空间。 这通常是主程序集中的一种类型(例如代码隐藏文件中的页面)。然后我们可以使用该类型的程序集。 如果所有其他方法均失败,则回退到 GetExecutingAssembly()。

这种方法仍然存在潜在问题,但它适用于我们的应用程序。

    private const string AspNetNamespace = "ASP";

    private static Assembly getApplicationAssembly()
    {
        // Try the EntryAssembly, this doesn't work for ASP.NET classic pipeline (untested on integrated)
        Assembly ass = Assembly.GetEntryAssembly();

        // Look for web application assembly
        HttpContext ctx = HttpContext.Current;
        if (ctx != null)
            ass = getWebApplicationAssembly(ctx);

        // Fallback to executing assembly
        return ass ?? (Assembly.GetExecutingAssembly());
    }

    private static Assembly getWebApplicationAssembly(HttpContext context)
    {
        Guard.AgainstNullArgument(context);

        object app = context.ApplicationInstance;
        if (app == null) return null;

        Type type = app.GetType();
        while (type != null && type != typeof(object) && type.Namespace == AspNetNamespace)
            type = type.BaseType;

        return type.Assembly;
    }

更新: 我已将此代码整合到 GitHub 上的一个小项目中和 NuGet .

关于c# - 使用程序集中的 Web 应用程序版本号 (ASP.NET/C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756031/

相关文章:

c# - 创建没有 BOM 的文本文件

C# 应用程序进程在一段时间后挂起

c# - 当我编辑代码时 ASP.NET 没有任何变化

.net - Azure 网站(标准)SSL 证书

javascript - ASP.NET - 用于引用 .CSS 和 .JS 的路径

C# ToolStrip 插入标准菜单标准图标位置

c# - 如何在mvc6中启用https

c# - .cs 文件是否在 .vbproj 下编译?

c# - 使用 JavaScript 将 visible 属性设置为 false 时删除空白区域

asp.net - 在 ASP.NET 的 ListView 中创建自定义按钮