Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 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 the contents of the URL.

Various articles explain how to use ASP.NET Routing to branch to existing pages on the web server.

What I would like to do is create the 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 saying "Response is not available in this context." at the Response.Write statement.

How to proceed?

UPDATE: In the end, I went with an approach based on IHttpModule, which turned out to be rather easy.

like image 282
ObiWanKenobi Avatar asked Jan 25 '09 11:01

ObiWanKenobi


3 Answers

You can't write to the response from an IRouteHandler - it's way too early during the request life cycle. You should only write to the response from within the IHttpHandler, which is what the Page is.

As is shown in other examples, you'll have to get a page instance from somewhere that has all the necessary content.

Here's how you can load an existing page:

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

Or you can create one from scratch:

Page p = new Page();
p.Controls.Add(new LiteralControl(
    @"<html>
      <body>
          <div>
              This is HTML!
          </div>
      </body>
      </html>"));
like image 85
Eilon Avatar answered Nov 18 '22 22:11

Eilon


Instead of trying to write directly to the response, you might want to simply add controls to the page. Since the page is brand-new and has no markup, you may have to add all of the HTML elements to make it legal HTML in order to get it rendered correctly. Having never tried this, I have no idea if it 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 required HTML, HEAD, and BODY tags. It might be better to create a base page that has skeleton markup that you can just add your controls to and use the BuildManager as in the example to instantiate this page, then add your controls.

like image 35
tvanfosson Avatar answered Nov 18 '22 23:11

tvanfosson


Put requestContext before Response.Write, so requestContext.Response.Write

like image 1
Ciaro Avatar answered Nov 19 '22 00:11

Ciaro