我試圖在運行時查找頁面請求的程序集。我使用的代碼爲Get current System.Web.UI.Page from HttpContext?,適用於大多數呼叫,但存在問題。從當前上下文中查找頁面或頁面組合
如果在我的aspx.cs中,我實例化一個類變量,在我的類的頂部HttpContext.Current.CurrentHandler
爲空。
例
我有一個名爲Business.dll
與函數來獲取頁類型按照上述SO問題一個DLL。
在我的網頁,在Default.asp的我FrontEnd.dll
有以下電話:
public partial class FrontEnd: Page
{
private readonly Type _t = Business.GetPageType();
上面的代碼返回HttpContext.Current.CurrentHandler爲空和返回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()
返回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;
}
雖然它的工作原理,它似乎是錯誤的,如果經常打電話會有潛在的性能影響。
這是有道理的。猜猜我可能必須選擇重新編寫代碼並使用約定,您不能在類中自行初始化變量,但必須在OnInit或類似過程中執行。謝謝。 – 2012-02-06 13:46:57