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?
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.
Yes it is:
void Page_Load(object sender, System.EventArgs e)
{
// Do some things before calling the original Page_Load
base.Page_Load(sender, e);
// Do some things after calling the original Page_Load
}
The reason this works is that the ASP.Net framework operates on the model where the .aspx file gets compiled up into a class that inherits from the class defined in your code behind file (actually the class defined by the Inherits
attribute on the page tag)
<%@ Inherits="WebApplication1._Default" ...
You can also try to use PreLoad
method. Those get called before Page_Load
and might be a cleaner way to handle things.
This works for me.
<script language="CS" runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Response.Write("additional stuff");
}
</script>
精彩评论