Search code examples
asp.netwebforms-routing

ASP.NET How do you stop the underlying Web Form in a routing application from being accessed directly?


Imagine a Web Forms application with routing. A clean page name like:

http://www.mywebsite.com/home

Might have an underlying of URL of:

http://www.mywebsite.com/page.aspx?id=3

If a user enters http://www.mywebsiter.com/page.aspx?id=3 into a browser, I need to redirect to http://www.mywebsite.com/home

Is this possible to do? I can't work out a way to do this as the routing engine is not executed for a physical page and in the page.aspx Page_Load method I have no way of knowing whether the URL was entered directly or was the result of a route.


Solution

  • You can use the Page.RouteData.Values collection to detect if the page is being loaded due to routing, rather than a direct URL. That can be done in Page_Load().

    If there are route data values (you would likely check for values that you would know should exist), then they are fine. If there are no route data values, the page has loaded 'directly', and you should redirect them.