Calling the original Page_Load function from inline code

Martin picture Martin · Jul 7, 2011 · Viewed 10.2k times · Source

I like to Monkey patch a ASPX website so that I can add stuff to the Page_Load method within a compiled assembly.

My first thought was to add a script tag containing a second Page_Load method to the ASPX file like so:

<script language="CS" runat="server">
void Page_Load(object sender, System.EventArgs e) 
{
     // do some stuff in addition to the original Page_Load method
}
</script>

But it looks like only the Page_Load method from the inline code will be executed and not the one from the original code-behind file (within the compiled assembly).

Is it possible to call the original method from within my inline code? Or is there any other way to add stuff that should run directly after the Page_Load method was called from within inline code without modifying the existing assembly?

Answer

SWeko picture SWeko · Jul 7, 2011

The asp.net model is that the page declared in the .aspx file is actally a descendant class from the class that inherits from System.Web.UI.Page declared in the .aspx.cs file.

So your Page_Load method is called because it basically hides the original Page_Load method. Following that logic, you could do:

<script language="CS" runat="server"> 
void Page_Load(object sender, System.EventArgs e)  
{      
   base.Page_Load(sender, e);
   // do some stuff in addition to the original Page_Load method 
} 
</script> 

There are no accessibility issues because asp.net by default declares Page_Load and similar methods as protected so descendant classes can call them.