LearnFast.Ninja

ASP.NET URL rewriting tutorial and sample code

This tutorial will show you how to build URL rewrite in ASP.NET with sample code and step by step instructions.

Step 1: Let me introduce you to the RewritePath function.
HttpContext.Current.RewritePath(Current_URL_After_Changes);

Step 2: Create your Url_Rewrite class.

/// <summary>

/// Url Rewrite class

/// </summary>

public static class Url_Rewrite

{

    /// <summary>

    /// Use this from Global.asax - Application_BeginRequest

    /// </summary>

    /// <example>"/article/id/1513/" to "article.aspx?id=1513"</example>

    public static void Route_URLs()

    {

        string Current_URL = HttpContext.Current.Request.Url.PathAndQuery.ToLower();

 

        // Page Name ----------------------------------------------

        if (Current_URL.Contains("/article/"))

        {

            string pattern = "/article";

            string replacement = "/article.aspx";

            Regex rgx = new Regex(pattern);

            Current_URL = rgx.Replace(Current_URL, replacement);

        }

 

        // id -----------------------------------------------------

        string id_pattern = "/id/(.*)/";

        if (Regex.Match(Current_URL, id_pattern).Success == true)

        {

            string id = Regex.Match(Current_URL, id_pattern).Groups[1].Value;

            string replacement = "?id=" + id;

            Regex oRegex = new Regex(id_pattern);

            Current_URL = oRegex.Replace(Current_URL, replacement);

        }

 

        HttpContext.Current.RewritePath(Current_URL);

    }

 

    /// <summary>

    /// Encode URL

    /// </summary>

    public static string Create_Friendly_Url(string Page_Name, string Page_Id, string Page_Title)

    {

        // Example: /article/id/1513/

        string New_URL = "/" + Page_Name + "/id/" + Page_Id + "/";

        return New_URL;

    }

 

}// end class


Step 3: Call the route URLs function from Global asax.

protected void Application_BeginRequest(object sender, EventArgs e)

{

    Url_Rewrite.Route_URLs();

}


Step 4: Create friendly URL when you create link in your site.

Result:



IIS Error: HTTP Error 404.0 - Not FoundThe resource you are looking for has been removed, had its name changed, or is temporarily unavailable.


Solution - IIS configuration: if you get 404 error enter this to your web.config (after </system.web>), and use Framework 4.0 +

  <system.webServer>

     <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>

Tags

asp.net

url-rewrite url-rewriting asax global-asax global rewritepath regex regular-expression replace match