Creating System.Web.UI.Page programmatically in IHTTPHandler

I am trying to use the ASP.NET (3.5) Routing Module functionality to create custom pages based on URL content.

Various articles such as this one: http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx explain how to use ASP.NET Routing to go to existing pages on a web server.

What I would like to do is create a page on the fly using code.

My first attempt looks like this:

public class SimpleRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { string pageName = requestContext.RouteData.GetRequiredString("PageName"); Page myPage = new Page(); myPage.Response.Write("hello " + pageName); return myPage; } } 

But this throws an HTTPException, which says, "The response is not available in this context." in the Response.Write statement.

How to act?

UPDATE: In the end, I chose an approach based on IHttpModule, which turned out to be quite simple.

+6
routing
source share
3 answers

You cannot write an answer from IRouteHandler - this is too early during the request life cycle. You should write only the answer from IHttpHandler , which is Page .

As shown in other examples, you will need to get a page instance somewhere that has all the necessary content.

Here you can load an existing page:

 Page p = (Page)BuildManager.CreateInstanceFromVirtualPath("~/MyPage.aspx"); 

Or you can create it from scratch:

 Page p = new Page(); p.Controls.Add(new LiteralControl( @"<html> <body> <div> This is HTML! </div> </body> </html>")); 
+8
source

Instead of directly writing a response, you can simply add controls to the page. Since the page is brand new and free of markup, you may need to add all the HTML elements to make it legal HTML in order to get it right. Without trying this, I have no idea if this will work.

  Page myPage = new Page(); page.Controls.Add( new LiteralControl( "hello " + pageName ) ); return myPage; 

It’s not clear to me that this will have the necessary HTML, HEAD and BODY tags. Perhaps it would be better to create a basic page with skeleton markup, with which you can simply add your controls and use the BuildManager, as in the example to create an instance of this page, and then add your controls.

+1
source

Put requestContext before the response. Record, therefore requestContext.Response.Write

+1
source

All Articles