Want to load your ASP.NET page routes from an XML file? Here is a sample file and a short snippet of code to load them. This supports not only basic page routes, but default items and route constraints.
Have fun!
<?xml version="1.0" encoding="utf-8" ?>
<pageRoute routeExisting="true">
<routes>
<!-- route with no defaults or constraints -->
<route name="HomePage">
<url>home</url>
<file>~/default.aspx</file>
</route>
<!-- route with defaults -->
<route name="FAQView">
<url>faqs/{id}</url>
<file>~/faqs/ViewFAQ.aspx</file>
<defaults>
<default key="id" value="1000" />
</defaults>
</route>
<!-- route with constraints -->
<route name="ProductView">
<url>products/view/{id}</url>
<file>~/products/ViewProduct.aspx</file>
<constraints>
<constraint key="id" value="\d+" />
</constraints>
</route>
</routes>
</pageRoute>
Code:
private void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
string path = Path.Combine(
Server.MapPath("~/App_Data"),
"PageRoute.xml");
if (File.Exists(path))
{
XElement xmlPageRoutes = XElement.Load(path);
routes.RouteExistingFiles = (bool)xmlPageRoutes.Attribute("routeExisting");
foreach (XElement xmlRoute in xmlPageRoutes.XPathSelectElements("routes/route"))
{
RouteValueDictionary defaults = new RouteValueDictionary();
foreach (XElement def in xmlRoute.XPathSelectElements("defaults/default"))
{
defaults.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
}
RouteValueDictionary constraints = new RouteValueDictionary();
foreach (XElement def in xmlRoute.XPathSelectElements("constraints/constraint"))
{
constraints.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
}
routes.MapPageRoute(
(string)xmlRoute.Attribute("name"),
(string)xmlRoute.Element("url"),
(string)xmlRoute.Element("file"),
true,
defaults,
constraints);
}
}
}
No comments:
Post a Comment