如何在引用的程序集中获取调用 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;
}
关于c# - 使用程序集中的 Web 应用程序版本号 (ASP.NET/C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756031/