【发布时间】:2012-02-06 08:50:08
【问题描述】:
我试图在运行时查找页面请求的程序集。我使用了Get current System.Web.UI.Page from HttpContext? 的代码,它适用于大多数呼叫,但存在一个问题。
如果我在我的 aspx.cs 中实例化类顶部的类变量 HttpContext.Current.CurrentHandler 为 null。
示例
我有一个名为 Business.dll 的 DLL,它具有根据上述 SO 问题获取页面类型的功能。
在我的页面中,FrontEnd.dll 中的 default.asp 我有以下调用:
public partial class FrontEnd: Page
{
private readonly Type _t = Business.GetPageType();
上面的代码返回 HttpContext.Current.CurrentHandler 为 null 并且 HttpContext.Current.ApplicationInstance 返回 HttpApplication 作为类型,因此 System.Web 作为程序集。
如果我这样写:
public partial class FrontEnd: Page
{
readonly Type _t;
protected override void OnInit(EventArgs e)
{
_t = Business.GetPageType();
它工作得很好,我得到了对 CurrentHandler 和页面的引用。我当然可以重构所有地方并将变量初始化移动到 OnInit,但这需要应用程序中的约定和更高程度的维护。
使用Assembly.GetEntryAssembly() return null 作为示例,Assembly.GetExecutingAssembly() 返回 Business.dll,所以我也不能使用它们。
是否有其他方法可以找到类型/dll,也许使用请求 URL 来查找它源自的类型/dll?
[更新]
到目前为止,我有这段代码,因为我所有的 dll 都使用已知密钥签名(不包括检查签名密钥的额外方法):
StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();
Assembly firstAssembly = null;
foreach (StackFrame stackFrame in stackFrames)
{
var method = stackFrame.GetMethod();
Type t = method.DeclaringType;
if (t != null && t.Assembly.Is(SignedBy.Me))
{
firstAssembly = t.Assembly;
}
}
if( firstPzlAssembly != null)
{
return firstPzlAssembly;
}
虽然它有效,但它似乎是错误的,如果经常调用,可能会对性能造成影响。
【问题讨论】: