Smit Shah

ASP.Net URL Rewrite using Global.asax

I built a Asp.Net website with the home page (default.aspx) having the following code

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication1._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
      <title></title>
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            <a href="/Profile/Smit/Shah/www.smitshah.com/">Smit Shah</a>
         </div>
      </form>
   </body>
</html>
Ofcourse the page does not exist in the physical directory structure
So to handle the URL rewrite only for pages that start with a "/Profile/" keyword I add the following block of code on the global.asax Application_BeginRequest event
Dim RequestedURL As String = Request.ServerVariables("URL")
If RequestedURL.StartsWith("/Profile/") Then
    Dim URLParts As String() = RequestedURL.Split("/")
    Context.RewritePath("/UserDetails.aspx?FirstName=" & URLParts(2) & "&LastName=" & URLParts(3) & "&Website=" & URLParts(4))
End If
So this way I check to make sure that only the profile pages go through the url rewrite logic above, all other pages are processed as usual

and finally to make sure the source code's <form> tag does not show the rewritten url we add the following block of code
form1.Action = Request.RawUrl

And this is the code for the UserDetails.aspx page
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="UserDetails.aspx.vb" Inherits="WebApplication1.UserDetails" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
      <title></title>
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            First Name: <%=Request("FirstName") %>
            <br />
            Last Name: <%=Request("LastName") %>
            <br />
            Website: http://<%=Request("Website")%>
         </div>
      </form>
   </body>
</html>







                                                                                         
This is a personal weblog. The opinions expressed here represent my own and not those of my employer. For accuracy and official reference refer to MSDN/ TechNet/ BOL /Other sites that are authorities in their field. Me or employer do not endorse any tools, applications, books, or concepts mentioned on the site. I have documented my personal experience on this site. The information on this site may not be up to date or accurate at times, if you are not sure or have a question, please contact me to verify information.