Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ReWrite URL (a little) 3

Status
Not open for further replies.

iskool

Programmer
Oct 11, 2006
4
0
0
JP
Dear All,

I need to ReWrite a URL and thus have been reading about this. It seems there are a number of ways to do it and so I think I need some advice about how to do it in my scenario.
I probably only need a function to do this but here goes..

When a user registers they are given their own space at
Mysite.com/?Username
This works because it defaults to
MySite.com/Default.aspx?Username and I get their real site value by matching the URL from the DB.

The whole site is Ajaxed and so the URL never changes.

What I would like to do is offer the user the url
MySite.com/Username (without the question mark)

So all I need to do is ReWrite the URL by adding the question mark.

All help and advice most appreciated.

Cheers,
J



 
in the global.asax:
Code:
<%@ Application Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

<script runat="server">
    

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        If Not File.Exists(Request.PhysicalPath) And InStr(Request.PhysicalPath, "WebResource.axd") = 0 Then
            Dim sRequestedURL As String = Request.RawUrl
            Dim strFile As String = Right(sRequestedURL, sRequestedURL.Length - InStrRev(sRequestedURL, "/"))
            Dim dbconnection As SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("tktConnectionString").ConnectionString)
            Dim contentID As Integer
            Try
                Dim pageCmd As SqlCommand = New SqlCommand("pr_get_ID", dbconnection)
                pageCmd.CommandType = CommandType.StoredProcedure
                pageCmd.Parameters.AddWithValue("@strFile", strFile)
                dbconnection.Open()
                contentID = pageCmd.ExecuteScalar()
            Catch ex As Exception
            Finally
                dbconnection.Close()
            End Try
            Dim sTargetURL As String = "~/default.aspx?id=" + contentID.ToString()
            Context.RewritePath(sTargetURL, False)
        End If
    End Sub

</script>

Basically, this gets the value after the last '/' which would be username in your example. It then looks up the id in the database based on the username. then it rewrites the path to go to the correct page, but the user only sees the url they typed in. Relative links and form action may get messed up. You can fix this with Javascript.
 
Mark,

Valid point. Probably a good idea to check for a trailing '/'. I am not sure this is the best method or not. I, too, looked all around for the 'right' solution a while back. I put this together and it works for my scenario where all my content is stored in a db. My url's are default.asp?id=123, where the id identifies the content in the db. With the code I posted, the user can use mysite.com/contact and the site will look up contact in the db, rewrite the path to default.aspx?id=123 and the user and search engines will know no different. this solution does not reallly handle directory depth and, as mentioned, it can mess with form action and relative links.

Also the 'WebResource.axd' check is so that the postbacks don't get filtered.

I posted the code in hopes that someone may have a cleaner better way or tweak it or at least as a starting point for iskool. It works in my scenario. That I know.
 
Another way would be to use a HttpModule to perform the same "interception" of the url that is generated and redirect that way. You'll still have to perform the check to see what they are accessing though and I think that's where your method could probably be improved (either by checking for the extra "/" or even splitting the string and checking each split). It just seems that at the moment it isn't particularly robust, especially if the user is typing in a URL.

Scott Guthrie has a great article on URL Rewriting (and the different approaches you can take to implement them) and you'll notice how he points out that IIS7 make this a much easier task.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Thanks for the article. Star-worthy.
 
sorry, i was tired and didn't type the whole thing.

In order for this to work, it has to go through the aspnet dll... three choices to achieve that: 1. use 'mySite.com/anything.aspx or 2. map a different extension to go to the dll in the IIS or 3. have extensionless url's route thru the aspnet dll. I have never tried the third option, but I believe it is possible.

I use the first option (.aspx)
 
Thanks mbiro,

You set me off on a voyage of discovery {a star for that} and I found this link on extensionless-urls

I set up my IIS 404 for this site locally and it works great.

So in the Global I have

Code:
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
       
        Dim sRequestedURL As String = HttpContext.Current.Request.Url.AbsolutePath
        
        If (sRequestedURL.Contains("404.aspx")) Then
            
            Dim sRaw As String = Request.RawUrl
            Dim strFile As String = Right(sRaw, sRaw.Length - InStrRev(sRaw, "/"))
            
            Context.RewritePath("~/default.aspx?" & strFile & "", False)
            
        Else
            'do nothing /continue...
        End If
       
    End Sub

And now I process the database stuff in the default page

Code:
Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs)

        MyBase.OnPreInit(e)

        ' ==========================================================
        Try

            Dim _Domain As String = Request.Url.ToString()
   
            Dim _sInt As UsersDB = New UsersDB
            Dim sInt As Integer = _sInt.GetsIntByDomain(_Domain)
            If sInt > 0 Then
                hdnID.Value = sInt
            Else
                hdnID.Value = 1 'default
            End If

        Catch ex As Exception
            hdnID.Value = 1 'default
        End Try

    End Sub


Cheers,
Jon





 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top