Using the Web Application version number from an assembly (ASP.NET/C#)

后端 未结 12 1015
我寻月下人不归
我寻月下人不归 2020-12-07 18:39

How do I obtain the version number of the calling web application in a referenced assembly?

I\'ve tried using System.Reflection.Assembly.GetCallingAssembly().GetName

12条回答
  •  我在风中等你
    2020-12-07 19:19

    Just in case anyone is still interested; this should do the trick and should be a tad safer than just taking the BaseType of ApplicationInstance to get your hands on the Global.asax implementation.

    Global.asax is always compiled into the same assembly as the assembly attributes from AssemblyInfo.cs, so this should work for all web applications that define a Global.asax.

    For those that don't define their own Global.asax, it will fall back to the version of the generated global_asax type, which is always 0.0.0.0, and for applications that aren't web applications, it will just return no version at all.

    Bonus; using the BuildManager class does not require an active HttpContext instance, which means you should be able to use this from application startup code as well.

    public static Version GetHttpApplicationVersion() {
      Type lBase = typeof(HttpApplication);
      Type lType = BuildManager.GetGlobalAsaxType();
    
      if (lBase.IsAssignableFrom(lType))
      {
        while (lType.BaseType != lBase) { lType = lType.BaseType; }
        return lType.Assembly.GetName().Version;
      }
      else
      {
        return null;
      }
    }
    

提交回复
热议问题