Url Rewriting in ASP.NET

Unknown | 9:35 AM |

web.config



<?xml version="1.0"?>

<configuration>
    <configSections>
        <section name="rewriter"
        requirePermission="false"
        type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
    </configSections>
 <system.web>
        <httpModules>
            <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
        </httpModules>
  <urlMappings enabled="true">
   <add url="~/Home" mappedUrl="~/Default.aspx?page=Home"/>
   <add url="~/About" mappedUrl="~/Default.aspx?page=About"/>
  </urlMappings>

        <compilation debug="true" targetFramework="4.0"/>
 </system.web>
    <system.webServer>

        <modules runAllManagedModulesForAllRequests="true">
            <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
        </modules>

        <validation validateIntegratedModeConfiguration="false" />

    </system.webServer>
    <rewriter>
        <rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
    </rewriter>
</configuration>


Global.asax


<%@ Application Language="C#" %>

<script runat="server">

    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 routeCollection)
    {
        routeCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");
        routeCollection.MapPageRoute("RouteForProducts", "Products/{PId}", "~/Products.aspx");
    }
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
     
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
     
</script>

UrlRewriting.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for UrlRewriting
/// </summary>
public class UrlRewriting
{
 public UrlRewriting()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    public  string GenerateURL(object Title, object strId)
    {
        string strTitle = Title.ToString();

        #region Generate SEO Friendly URL based on Title
        //Trim Start and End Spaces.
        strTitle = strTitle.Trim();

        //Trim "-" Hyphen
        strTitle = strTitle.Trim('-');

        strTitle = strTitle.ToLower();
        char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
        strTitle = strTitle.Replace("c#", "C-Sharp");
        strTitle = strTitle.Replace("vb.net", "VB-Net");
        strTitle = strTitle.Replace("asp.net", "Asp-Net");

        //Replace . with - hyphen
        strTitle = strTitle.Replace(".", "-");

        //Replace Special-Characters
        for (int i = 0; i < chars.Length; i++)
        {
            string strChar = chars.GetValue(i).ToString();
            if (strTitle.Contains(strChar))
            {
                strTitle = strTitle.Replace(strChar, string.Empty);
            }
        }

        //Replace all spaces with one "-" hyphen
        strTitle = strTitle.Replace(" ", "-");

        //Replace multiple "-" hyphen with single "-" hyphen.
        strTitle = strTitle.Replace("--", "-");
        strTitle = strTitle.Replace("---", "-");
        strTitle = strTitle.Replace("----", "-");
        strTitle = strTitle.Replace("-----", "-");
        strTitle = strTitle.Replace("----", "-");
        strTitle = strTitle.Replace("---", "-");
        strTitle = strTitle.Replace("--", "-");

        //Run the code again...
        //Trim Start and End Spaces.
        strTitle = strTitle.Trim();

        //Trim "-" Hyphen
        strTitle = strTitle.Trim('-');
        #endregion

        //Append ID at the end of SEO Friendly URL
        strTitle = "~/"+Title.ToString().Replace(".aspx","")+"/" + strTitle + "-" + strId + ".aspx";

        return strTitle;
    }
}


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body>
    <form id="form1" runat="server">
    <div>

        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Home">Home</asp:HyperLink>
        <br />
        <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/About">About</asp:HyperLink>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Customer</asp:LinkButton>
        <br />
        <asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click" >Products</asp:LinkButton>
    </div>
    </form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
 

    UrlRewriting ur = new UrlRewriting();

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Request.QueryString["page"];
    }
 
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect(ur.GenerateURL("Customer.aspx", 1));
    }
 
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        Response.Redirect(ur.GenerateURL("Products.aspx", 1));
    }
}

Customer.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Customer.aspx.cs" Inherits="Customer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Customer</asp:LinkButton>
    </div>
    </form>
</body>
</html>

Customer.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Customer : System.Web.UI.Page
{
    UrlRewriting ur = new UrlRewriting();
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = Page.RouteData.Values["Id"].ToString();

        Response.Write("<h1>Customer Details page</h1>");
        Response.Write(string.Format("Displaying information for customer : {0}", id));

    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect(ur.GenerateURL("Customer.aspx",2));

    }
 

}

Products.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Products.aspx.cs" Inherits="Products" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>


Products.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Products : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = Page.RouteData.Values["PId"].ToString();

        Response.Write("<h1>Products Details page</h1>");
        Response.Write(string.Format("Displaying information for Products : {0}", id));
    }
}

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....