ASP.NET MVC: How to obtain assembly information from HtmlHelper instance?

后端 未结 3 1654
耶瑟儿~
耶瑟儿~ 2021-02-20 04:50

I have an HtmlHelper extension method in an assembly separate from my MVC application assembly. Within the extension method I would like to get the version number of the MVC app

3条回答
  •  迷失自我
    2021-02-20 05:19

    This is a notoriously evil thing - because unfortunately there's no one specific reliable way to do it.

    Since it's an MVC application, however, the chances are that it has a Global.asax.cs - therefore it has a locally defined HttpApplication class.

    From within an html helper you can get to this:

    public static string AppVersion(this HtmlHelper html)
    {
      var appInstance = html.ViewContext.HttpContext.ApplicationInstance;
      //given that you should then be able to do 
      var assemblyVersion = appInstance.GetType().BaseType.Assembly.GetName().Version;
      //note the use of the BaseType - see note below
      return assemblyVersion.ToString();
    }
    

    Note

    You might wonder why the code uses the BaseType of the application instance, and not simply the type. That's because the Global.asax.cs file is the primary type of the MVC application, but then Asp.Net dynamically compiles another HttpApplication type that inherits from that via the Global.asax.

    As I said earlier; this works in most MVC sites because they should all have an application class defined in a Global.asax.cs file by convention (because that's the way the project is set up).

提交回复
热议问题