I'm trying to find the assembly of a page request during runtime. I have used the code at Get current System.Web.UI.Page from HttpContext? which work for most calls, but there is an issue.
If in my aspx.cs I instantiate a class variable at the top of my class HttpContext.Current.CurrentHandler
is null.
Example
I have one DLL named Business.dll
with the function to get the Page type as per the above SO question.
In my page, default.asp in FrontEnd.dll
I have the following call:
public partial class FrontEnd: Page
{
private readonly Type _t = Business.GetPageType();
The above code return HttpContext.Current.CurrentHandler as null and HttpContext.Current.ApplicationInstance return HttpApplication as the type, and hence System.Web as the assembly.
If I however write it like this:
public partial class FrontEnd: Page
{
readonly Type _t;
protected override void OnInit(EventArgs e)
{
_t = Business.GetPageType();
it works just fine, and I get a reference to CurrentHandler and the page. I could of course refactor all places and move the variable initialization to OnInit, but this requires convention in the app and a higher degree of maintenance.
Using Assembly.GetEntryAssembly()
return null for the example and Assembly.GetExecutingAssembly()
return Business.dll, so I cannot use them either.
Is there possible another way to find the type/dll, perhaps using the Request Url to find the type/dll which it originates from?
[Update]
So far I have this code, as all my dll's are signed with a known key (not including the extra methods for checking the signing key):
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;
}
While it works, it seems wrong and will have a potential performance hit if called often.