Reputation: 6692
How to get the HttpHandler of an aspx page?
For instance, I have test.aspx with code behind public class Test : System.Web.UI.Page [...]
If I call new Test()
It doesn't return the exact same kind of HttpHandler that the one I get from HttpApplication.Context.Handler
which can be access while browsing to test.aspx.
FYI (and definitivelly not the question): I need that because I'll be doing complex thing using Server.Transfer(NewPageHandler)
Upvotes: 0
Views: 443
Reputation: 63742
Basically, in your case Test
is the parent of the actual Test.aspx
class (ie. the ASPX file is compiled into a class that inherits from Test
).
To get the Test.aspx
instance, one option is to use the compiler directly:
BuildManager.CreateInstanceFromVirtualPath("~/Test.aspx", typeof(Test));
Or you can use PageParser.GetCompiledPageInstance
as Murali Murugesan suggested, they're pretty much equivalent.
Note that this is not really supported ("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code."), but it does work mostly. I've actually switched to the default PageHandlerFactory
in my code, which is a lot more stable:
class LuPageHandlerFactory : PageHandlerFactory
{
public static LuPageHandlerFactory Instance = new LuPageHandlerFactory();
private LuPageHandlerFactory() { }
}
// Which lets me call this:
var handler =
LuPageHandlerFactory.Instance.GetHandler
(
HttpContext.Current, null, "~/Test.aspx", null
) as Test;
A cleaner approach is simply to use HttpContext.Current.RewritePath("~/Test.aspx");
and pass the data in HttpContext.Current.Items
.
My engine actually uses the last approach I mentioned as a fallback - if the LuPageHandlerFactory
approach throws SecurityException
, I fallback to RewritePath
.
You should also handle HttpCompileException
.
Upvotes: 1
Reputation: 22619
You can get a compiled instance of your page
System.Web.UI.PageParser
.GetCompiledPageInstance("~/YourPage.aspx",
HttpApplication.Server.MapPath("~/YourPage.aspx")
, HttpApplication.Context);
Upvotes: 1