Setting up ASP.NET webforms to use ASP.NET 4.0s new native routing setup was really easy to do on a recent project I completed. There were only one or two gotcha's but once you know about them you won't have any problems setting routing up on your own projects.
For the tutorial below I will assume that you have asp.net 4.0 installed and that you have an ASP.NET webforms site or project already created. For this example I will create routing for a very simple site that has the following pages:
- Default
- News
- NewsDetails (expects an ID value to be passed through to it)
- error
We will setup our demo so that the above pages are routed to the following addresses:
- /home
- /news
- /news/news title/news id
- /error
Step 1: If not already created, setup a Global.asax page.
You can do this by right clicking on the name of your project in solution explorer and selecting Add New Item. Select Global Application Class from the list and leave the page called Global.asax and click Add.
Step 2: Adjust the code in the global.asax file so it looks a little like the example below:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.MapPageRoute("Error", "error", "~/error");
routes.MapPageRoute("Home", "home", "~/default");
routes.MapPageRoute("News", "news", "~/news");
routes.MapPageRoute("NewsDetails", "news/{categoryname}/{categoryid}", "~/newsdetails");
routes.MapPageRoute("defaultRoute", "{*value}", "~/error"); // wildcard mapping
}
Step 3: On your aspx pages adjust your page links so that they are generated as follows for simple page links:
<a href="<%: Page.GetRouteUrl("Home", null)%>" title="Home">Home</a>
<a href="<%: Page.GetRouteUrl("News", null)%>" title="Home">Home</a>
The above code tells .net to look in the routing table in the Global.asax page to get the actual file for the location requested. The handy thing about using this GetRouteUrl class is that you are not hardcoding filenames into your links which can be handy later on if you need to change where links have to go. If you want to pass any querystring data, like we need to do for the news details page in our example, then you can setup the link like below:
<a href="<%: Page.GetRouteUrl("News", null)%>/<%# HttpUtility.UrlEncode(NewTitleValue)%>/<%# Eval("NewsID") %>">Read full article ...</a>
The link above is taking the News Title and News ID values and placing them into the link so that we can get the relevant info on the newsdetails page. We are URL encoding the title so that we can ensure the text used in the title will be a properly formatted link. If we didn't do this then spaces or special characters in the title would case the link to either fail or look horrible.
Step 4: how do you read in querystring values from your routing link?
I have setup a newsdetails page that looks for a News ID value to be passed to it so we can get the relevant details from the database. In the above examples you have created the link so that the ID value we need will be passed in the categoryid field name at the end of the link. Reading in this value on the newsdetails.cs page is as easy as:
string idValue = Page.RouteData.Values["categoryid"] as string;
Step 5: adjust the links to CSS, Images and JavaScript
At this point you have seen how to setup basic routing for your pages, how to pass through querystring and read them but there is one last step you need to do before you can be on your merry way. Your CSS paths, Image paths and JavaScript paths all need to be told where to get the files from now that you have routing setup.
When the user goes to "news/news title/news id" you will find that your images and css fail to load because the paths would be output in the html as "news/news title/news id/css" instead of "root level of your site/css". To get around this issue we can simply tell .net to map the files to the correct location no matter what url setup we have. All you need to do is something like this:
<%: Page.ResolveUrl("~/images/pic1.jpg")%>
<%: Page.ResolveUrl("~/css/styles.css")%>
Using the tilda (~) will tell .net to start at the root directory of your website.
Step 6: Some little things to watch out for!
Redirect the user if the URL they enter is incorrect.
You might have noticed that in the first step I had a line in there to handle wildcard mapping (routes.MapPageRoute("defaultRoute", "{*value}", "~/error");). This can be handy if you want to bring your users to a specific page on your site if they type in the wrong address. In this example, a mistyped URL would go to our error page but you could easily set this up to go to your homepage or anywhere else on your site.
Make sure your folder name does not contain a dot (.) in the name when running locally.
This one drove me a little nutty while testing locally until I found the issue. I kept getting a Page Cannot Be Found error message. It turns out that .net does not like it when a folder name has a dot in it when routing is enabled for some reason. I usually have my folders called 'domainname.com' which is what gave me the error. Renaming the folder to 'domainnamecom' sorted out this weird issue.
There you have it. A nice simple example that covers most of the basics to get you up and running asp.net 4.0 routing on your new webforms website.
Member discussion