Search engines hate query strings.
For example, say you have a website that sells widgets. You have four types of widgets: red, green, blue and black. You have a page titled Inventory.aspx that accepts a query string to show each of the widgets, like this:
www.MyWidgetSite.com/Widgets.aspx?Type=Red
To make this more SEO friendly, you could have a URL like this:
www.MyWidgetSite.com/Widgets/Red
That allows a search engine to index the site easier, and to more easily identify relevant content for search queries.
The old way would have been to actually create those subdirectories and drop a default page into each one, but by using URL Routing you can create an "alias" that the framework can decipher behind the scenes and direct to the correct page.
You'll add a new route to the Global.asax file. Start by adding a using directive:
using System.Web.Routing;
In the Application_Start method, call a new method, passing it a RouteCollection:
RegisterRoutes(RouteTable.Routes);
Then add that method:
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(routeName, routeUrl, physicalFile);
}
The parameters are:
- routeName - a friendly name for the route
- routeUrl - the new URL pattern than the route will use
- physicalFile - the original aspx page where you passed the querystring
So for our example above, it would look like:
routes.MapPageRoute("Widgets", "Widgets/{WidgetType}", "~/Widgets.aspx");
That's all that's needed in Global.asax to handle the routing; now you'll construct the new URLs. You could hardcode the URL, like:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Widgets/Red" Text="All Red Widgets" />
Or you could build the URL using a RouteURL expression:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%$RouteUrl:WidgetType=Red" Text="All Red Widgets" />
Finally, you have to have a way to retrieve the data that you were previously passing via querystring. You can do this via the Page.RouteData property:
Page.RouteData.Values["WidgetType"].ToString();
However, you probably don't want to completely replace the querystring functionality on the landing page - what if a user has a bookmark containing the querystring? Something like this would take care of both situations:
string widgetType = "";
if (Page.RouteData.Values.Count() > 0)
{
widgetType = Page.RouteData.Values["WidgetType"].ToString();
}
else
{
widgetType = Request.QueryString["Type"];
}
Technorati Tags: C#, ASP.Net
