URL rewriting in asp.net

what is URL rewriting ?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.

http://msdn.microsoft.com/en-us/library/ms972974.aspx 

why URL rewriting?

1) Make User Friendly and Secure URL

Example :  In your application, you create a page which display category information and it’s relevant category. At that time we normally passing a value via query string,

http://Site.com/category.aspx?categoryid=1. Any user play with URL, you can also do the URL Encryption. but sometime case is complex at that time it is not possible.

2) Make SEO Friendly URL

3) Usability & Maintainability

Use Of Browser file?

ASP.NET uses .browser files to determine the capabilities of the browser, and how to render markup to that browser.

Browser files are used to reduce the load of the page made by the view state by storing it in a server side session variable.

In particular Rewriting Module: Handling Post back with URL Rewriting.

what is ControlAdapter?

for more detail please check :

http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx

Create demo project for URL Rewriting:

Step 1:

Create Web application with (Asp.net 2.0 with c#)

Step 2:

Put two button in the form (default.aspx)

Put Below code for Button1_Click Event :

Response.Redirect("Default.aspx?id=1");

Put Below code for Button2 _Click Event:

Response.Redirect("/urlrewriting/FirstSection/Default.html");

Step 3: Run Application

once you press Button2 it give Error page.

Step 4:

Create Class FormRewriterControlAdapter.cs

   1: using System;

   2: using System.Data;

   3: using System.Configuration;

   4: using System.Web;

   5: using System.Web.Security;

   6: using System.Web.UI;

   7: using System.Web.UI.WebControls;

   8: using System.Web.UI.WebControls.WebParts;

   9: using System.Web.UI.HtmlControls;

  10:  

  11: public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter

  12: {

  13:     protected override void Render(HtmlTextWriter writer)

  14:     {

  15:         base.Render(new RewriteFormHtmlTextWriter(writer));

  16:     }

  17: }

  18:  

  19: public class RewriteFormHtmlTextWriter : HtmlTextWriter

  20: {

  21:     public RewriteFormHtmlTextWriter(HtmlTextWriter writer)

  22:         : base(writer)

  23:     {

  24:         this.InnerWriter = writer.InnerWriter;

  25:     }

  26:  

  27:     public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)

  28:         : base(writer)

  29:     {

  30:         base.InnerWriter = writer;

  31:     }

  32:  

  33:     public override void WriteAttribute(string name, string value, bool fEncode)

  34:     {

  35:         if (name == "action")

  36:         {

  37:             HttpContext Context = HttpContext.Current;

  38:             if (Context.Items["ActionAlreadyWritten"] == null)

  39:             {

  40:                 value = Context.Request.RawUrl;

  41:                 Context.Items["ActionAlreadyWritten"] = true;

  42:             }

  43:         }

  44:         base.WriteAttribute(name, value, fEncode);

  45:     }

  46: } 

 

Create Class MyHttpHandler.cs

   1: using System;

   2: using System.Data;

   3: using System.Configuration;

   4: using System.Web;

   5: using System.Web.Security;

   6: using System.Web.UI;

   7: using System.Web.UI.WebControls;

   8: using System.Web.UI.WebControls.WebParts;

   9: using System.Web.UI.HtmlControls;

  10:  

  11: public class MyHttpHandler : IHttpModule

  12:  

  13: {

  14:     public MyHttpHandler()

  15:     {

  16:         //

  17:         // TODO: Add constructor logic here

  18:         //

  19:     }

  20:  

  21:     #region IHttpModule Members

  22:  

  23:     public void Dispose()

  24:     {

  25:        

  26:     }

  27:  

  28:     public void Init(HttpApplication app)

  29:     {

  30:         app.BeginRequest += new EventHandler(Application_BeginRequest);

  31:     }

  32:  

  33:     private void Application_BeginRequest(object sender, EventArgs e)

  34:     {

  35:         System.Web.HttpApplication app = (System.Web.HttpApplication)sender;

  36:         string requestedUrl = app.Request.Path.ToLower();

  37:         string realUrl = GetRealUrl(requestedUrl);

  38:         if (!String.IsNullOrEmpty(realUrl))

  39:             app.Context.RewritePath(realUrl, false);

  40:     }

  41:  

  42:     private string GetRealUrl(string requestedUrl)

  43:     {

  44:         // Implement your own logic here

  45:         MyURL obj = new MyURL();

  46:         return obj.GetRealPath(requestedUrl);

  47:     } 

  48:     #endregion

  49: }

 

create Class MyURL.cs

   1:  

   2: using System;

   3: using System.Data;

   4: using System.Configuration;

   5: using System.Web;

   6: using System.Web.Security;

   7: using System.Web.UI;

   8: using System.Web.UI.WebControls;

   9: using System.Web.UI.WebControls.WebParts;

  10: using System.Web.UI.HtmlControls;

  11: using System.Collections.Generic;

  12:  

  13: /// <summary>

  14: /// Summary description for MyURL

  15: /// </summary>

  16: public class MyURL

  17: {

  18:     public MyURL()

  19:     {

  20:         //

  21:         // TODO: Add constructor logic here

  22:         //

  23:     }

  24:  

  25:     public string GetRealPath(string requestedUrl)

  26:     {

  27:         string path = "";

  28:         Dictionary<string, string> paths = GetPathsFromDatabase();

  29:         if (paths.ContainsKey(requestedUrl))

  30:             paths.TryGetValue(requestedUrl, out path);

  31:         return path;

  32:     }

  33:  

  34:     private static Dictionary<string, string> GetPathsFromDatabase()

  35:     {

  36:         Dictionary<string, string> paths = new Dictionary<string, string>();

  37:         paths.Add("/urlrewriting/FirstSection/Default.html".ToLower(), "/urlrewriting/Default.aspx?SectionID=1");

  38:         paths.Add("/urlrewriting/SecondSection/Default.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2");

  39:         paths.Add("/urlrewriting/FirstSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=1");

  40:         paths.Add("/urlrewriting/FirstSection/Page2.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=2");

  41:         paths.Add("/urlrewriting/SecondSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=1");

  42:         paths.Add("/urlrewriting/SecondSection/SubSection/AnotherOne/Page5.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=5");

  43:         paths.Add("/urlrewriting/Default.aspx".ToLower(), "/urlrewriting/Default.aspx");

  44:         return paths;

  45:     } 

  46: }

Register Http Handler in to Web.Config

   1: <system.web>

   2:         <httpModules>

   3:             <add name="MyHttpHandler" type="MyHttpHandler"/>

.Browser File

Add New .browser file from Add New Item.

   1: <browsers>

   2:     <browser id="NewBrowser" parentID="Mozilla">

   3:         <identification>

   4:             <userAgent match="Unique User Agent Regular Expression" />

   5:         </identification>

   6:  

   7:         <capture>

   8:             <userAgent match="NewBrowser (?'version'\d+\.\d+)" />

   9:         </capture>

  10:  

  11:         <capabilities>

  12:             <capability name="browser" value="My New Browser" />

  13:             <capability name="version" value="${version}" />

  14:         </capabilities>

  15:     </browser>

  16:  

  17:     <browser refID="Mozilla">

  18:         <capabilities>

  19:             <capability name="xml" value="true" />

  20:         </capabilities>

  21:     </browser>

  22: <!--FormRewrite Control Adapter-->

  23:     <browser refID="Default">

  24:         <controlAdapters>

  25:             <adapter controlType="System.Web.UI.HtmlControls.HtmlForm"

  26:                 adapterType="FormRewriterControlAdapter" />

  27:         </controlAdapters>

  28:     </browser>

  29: </browsers>

step 5: Run Application

Now Press Button 2:

http://localhost:2696/urlrewriting/FirstSection/Default.html and it is run.

 

Now made some change in to system. Remove browser file and click button2, after that made postback at that time above URL is change to original URL.

Reference Site :

For Detail Example :

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

 

Hope this help you.

Thnx

 

Leave a comment