I've read ASP.NET Routing… Goodbye URL rewriting? and Using Routing With WebForms which are great articles, but limited to simple, illustrative, "hello world"-complexity examples.
Is anyone out there using ASP.NET routing with web forms in a non-trivial way? Any gotchas to be aware of? Performance issues? Further recommended reading I should look at before ploughing into an implementation of my own?
EDIT Found these additional useful URLs:
A simple example of how to use routing in ASP.NET
Add to default.aspx 3 buttons -
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Second.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Pants");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Shoes");
}
Read query string on third page
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["Name"]);
}
Now if you run the program, you will be able to navigate to second and third form. This is how it used to be. Let's add routing.
Add new item - Global.aspx using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"HomeRoute",
"Home",
"~/Default.aspx"
);
routes.MapPageRoute(
"SecondRoute",
"Second",
"~/Second.aspx"
);
routes.MapPageRoute(
"ThirdRoute",
"Third/{Name}",
"~/Third.aspx"
);
}
In default.aspx modify protected void Button1_Click(object sender, EventArgs e) { // Response.Redirect("Second.aspx"); Response.Redirect(GetRouteUrl("SecondRoute", null)); }
protected void Button2_Click(object sender, EventArgs e)
{
//Response.Redirect("Third.aspx?Name=Pants");
Response.Redirect(GetRouteUrl("ThirdRoute", new {Name = "Pants"}));
}
protected void Button3_Click(object sender, EventArgs e)
{
// Response.Redirect("Third.aspx?Name=Shoes");
Response.Redirect(GetRouteUrl("ThirdRoute", new { Name = "Shoes" }));
}
Modify page load in third.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Request.QueryString["Name"]);
Response.Write(RouteData.Values["Name"]);
}
Run the program, Please note that url looks much cleaner - there are not file extensions in it (Second.aspx becomes just Second)
To pass more then one argument
add new button to default.aspx with the following code:
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect(GetRouteUrl("FourthRoute", new { Name = "Shoes" , Gender = "Male"}));
}
add the following code to global.asax
routes.MapPageRoute(
"FourthRoute",
"Fourth/{Name}-{Gender}",
"~/Fourth.aspx"
);
create Fourth.aspx page with the following page load:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Name is: " + RouteData.Values["Name"] + " and Gender is " + RouteData.Values["Gender"]);
}