<urlMappings> Example, Custom UrlRemapper Module in ASP.Net C#

The <urlMappings> configuration element, It remaps one page to another. e.g, if you have a database that contains a table of product categories and a table of products. You want your website’s users to request a URL that contains a product category and be able to see matching products. For example, if someone requests the /Products/ProductItem.aspx page, you want to display all the products in the ProductItem category.If someone requests the /Products/ProductItem.aspx page, you want to display all the products in the ProductItem category.

In that case, you need to use a wildcard when matching URLs. When someone requests any path that matches the pattern /Products/*, you want to redirect the user to a page where you can display matching products for the category specified in the path.
In this section, we create a custom HTTP module that remaps one URL to another. The module supports regular expression matching. Therefore it supports wildcard matches.

using System;
using System.Web;
using System.Xml;
using System.Web.Caching;
using System.Text.RegularExpressions;
namespace AspNetMapper
{
public class UrlRemapper : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
public void app_BeginRequest(Object s, EventArgs e)
{
// Get HTTP Context
HttpApplication app = (HttpApplication)s;
HttpContext context = app.Context;
// Get current URL
string currentUrl = context.Request.AppRelativeCurrentExecutionFilePath;
// Get URL Mappings
XmlDocument urlMappings = GetUrlMappings(context);
// Compare current URL against each URL from mappings file
XmlNodeList nodes = urlMappings.SelectNodes(“//add”);
foreach (XmlNode node in nodes)
{
string url = node.Attributes[“url”].Value;
string mappedUrl = node.Attributes[“mappedUrl”].Value;
if (Regex.Match(currentUrl, url, RegexOptions.IgnoreCase).Success)
context.RewritePath(mappedUrl);
}
}
private XmlDocument GetUrlMappings(HttpContext context)
{
XmlDocument urlMappings = (XmlDocument)context.Cache[“UrlMappings”];
if (urlMappings == null)
{
urlMappings = new XmlDocument();
string path = context.Server.MapPath(“~/UrlMappings.config”);
urlMappings.Load(path);
CacheDependency fileDepend = new CacheDependency(path);
context.Cache.Insert(“UrlMappings”, urlMappings, fileDepend);
}
return urlMappings;
}
public void Dispose() { }
}
}

The class implements the IHttpModule interface. An HTTP module is a special class that executes whenever you make a page request. HTTP Modules “Working with the HTTP Runtime.”
The module includes an Init() method. This method adds an event handler for the Application BeginRequest event. The BeginRequest event is the first event that is raised when you request a page.
The BeginRequest handler gets a list of URL remappings from an XML file named UrlMappings.config. The contents of this XML file are cached in memory until the UrlMappings.config file is changed on the hard drive.
The module iterates through each remapping from the XML file and performs a regular expression match against the current URL. If the match is successful, then the Context.RewritePath() method is used to change the current path to the remapped path.

Web.Config
<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”>
<system.web>
<httpModules>
<add name=”UrlRemapper” type=”AspNetMapper.UrlRemapper” />
</httpModules>
</system.web>
</configuration>



<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.IO” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
void Page_Load()
{
if (!Page.IsPostBack)
{
string category = Path.GetFileNameWithoutExtension(Request.RawUrl);
ltlCategory.Text = category;
srcData.SelectParameters[“Category”].DefaultValue = category;
}
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
.grid td,.grid th
{
padding:4px;
border-bottom:solid 1px black;
}
</style>
<title>Products</title>

</head>
<body>
<form id=”form1” runat=”server”>
<div>
<h1>
<asp:Literal
ID=”ltlCategory”
runat=”server” />
</h1>
<asp:GridView id=”GridShowData” DataSourceID=”srcData” CssClass=”grid” GridLines=”None” AutoGenerateColumns=”false” Runat=”server”>
<Columns>
<asp:BoundField HeaderText=”Product Name” DataField=”Name” />
<asp:BoundField HeaderText=”Price” DataField=”Price” DataFormatString=”{0:c}” />
</Columns>
</asp:GridView>
<asp:SqlDataSource
id=”srcData” ConnectionString=”<%$ ConnectionStrings:Products %>” SelectCommand=”SELECT Products.* FROM Products JOIN Categories ON Products.CategoryId=Categories.Id WHERE Categories.Name=@Category” Runat=”server”>
<SelectParameters>
<asp:Parameter Name=”Category” />
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

The Page_Load() event handler grabs the path of the original request, using the Request.RawUrl property. Next, it extracts the filename from the path, using the System.IO.Path.GetFileNameWithoutExtension() method. Finally, it assigns the name of the page (the category name) to a Label and SqlDataSource control. Products that match the category are displayed in a GridView control.
Tags: , , ,
Hot on Web:


About author