ASP.NET MVC:如何获取的HtmlHelper实例装配信息? [英] ASP.NET MVC: How to obtain assembly information from HtmlHelper instance?

查看:219
本文介绍了ASP.NET MVC:如何获取的HtmlHelper实例装配信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件的扩展的HtmlHelper方法从我的MVC应用程序组件分离。在扩展方法,我想获得MVC应用程序集的版本号。这可能吗?

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 application assembly. Is this possible?

调用组件的剃刀视图动态组装,这样于事无补。是否有嵌套的HtmlHelper,可以提供给我的MVC应用程序集的版本号内的一些对象吗?我一直在探索 HtmlHelper类文档但到目前为止避风港 t上找不到一个解决我的问题。

The calling assembly is the razor view dynamic assembly so that doesn't help. Is there some object nested within the HtmlHelper that can provide me with the version number of the MVC application assembly? I've been exploring the HtmlHelper class documentation but so far haven't found a solution to my problem.

谢谢!

推荐答案

这是出了名的邪恶的东西 - 因为不幸的是有没有一个具体的可靠的方式来做到这一点。

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

因为它是一个MVC应用程序,但是,机会是,它具有的Global.asax.cs - 因此具有本地定义的的HttpApplication

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.

从HTML帮助中,你可以得到这样:

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();
}

注意

您可能会问,为什么code使用 BASETYPE 应用程序实例,而不是简单的类型。这是因为的Global.asax.cs文件是MVC应用程序的主要类型,但随后Asp.Net动态编译通过在Global.asax。

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.

正如我刚才所说,这适用于大多数MVC网站,因为他们都应该有按照约定在的Global.asax.cs文件中定义的应用程序类(因为这是项目设置方式)。

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).

这篇关于ASP.NET MVC:如何获取的HtmlHelper实例装配信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆