views:

436

answers:

4

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, 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 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.

Any ideas on how to proceed?

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

A: 

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.

tvanfosson
A: 

Try calling Server.Transfer which will route to the ASPX page you specify while still maintaining the URL in the browser.

Mike Knowles
He is using ASP.NET Routing - there is no need for Server.Transfer.
Eilon
A: 

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

Ciaro
A: 

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>"));
Eilon