CraigWardman.com

[ Safe Rewriting URL Encoder ]

/Blog/Post

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

Safe Rewriting URL Encoder

Thursday, 30 October 2008


When using URL rewriting to make nice URLs without querystrings, it is useful to include a meaningful name for the page, i.e. the page title, in the URL itself. This helps usability in distinguishing pages and also aids search engines in spidering different content that may be generated by a single page on your server.

For some reason, the HttpUtility.UrlEncode and HttpUtility.HtmlEncode just dont cut it for making good URLs that are readable, optimized and work on the browser/server.

I have written my own class for cleaning/encoding text into a form that can be used as part of a URL that will be used in a rewriting engine.

Code:


Imports System.Text.RegularExpressions

Public Class UrlEncoder
Public Shared Function EncodeRewriteUrl(ByVal inputString As String) As String
Dim url As String = Regex.Replace(System.Web.HttpUtility.HtmlDecode(inputString.Replace(" ", "-")), "[^a-zA-Z0-9\-]", "")
While url.Contains("--")
url = url.Replace("--", "-")
End While
Return url
End Function
End Class



The idea here is that you pass in the text you want to use as your URL, and you receive a hyphenated URL containing only URL safe characters ready for use with your rewriting engine.

Example:

if..
pageId=1
pageTitle="A page about 'dogs' and 'cats' (also other things)"

and..
pageUrl=UrlEncoder.EncodeRewriteUrl(pageTitle & "-" & pageId & ".aspx")

then..
The page URL would be:

A-page-about-dogs-and-cats-also-other-things-1.aspx

Labels: , , , ,

Share This!



0 Comments:

Post a Comment

<< Home

CraigWardman.com