Allowing special characters (forward slash, hash, asterisk etc) in ASP.Net MVC URL parameters January 6
I’ve been getting into ASP.Net MVC a lot lately and there is plenty that is good about it.
One thing that is not good is the problems that MVC has when you have a special character (*,/,& etc) in your querystring.
Eg: Say you want to pass the param
url=http://google.com
MVC won’t like it - ‘/’ is a special character reserved as a separator for routes. But standard URL encoding it won’t work either:
url=http%3A%2F%2Fgoogle.com
MVC will still give a ‘HTTP Error 400 - Bad Request error’.
After looking around, it seems this error has been coming up a bit here and here and Phil Haack explains why standard encoding won’t work here.
One answer is to use base 64 encoding on any parameters that might contain the special characters.
Public Function MyURLEncode(ByVal sInString As String) As String
Dim sInStringNoSpaces As String = sInString.Replace(" ", "")
Dim sURLEncoded As String = HttpUtility.UrlEncode(sInString)
If sURLEncoded.Replace("+", "") = sInString.Replace(" ", "") Then
Return sURLEncoded
Else
Return "=" & ToBase64(sInString)
End If
End Function
Public Function MyURLDecode(ByVal sEncodedString As String) As String
If sEncodedString.StartsWith("=") = True Then
MyURLDecode = FromBase64(Mid$(sEncodedString, 2))
Else
MyURLDecode = sEncodedString.Replace("+", " ")
End If
End Function
Private Function ToBase64(ByVal sInString As String) As String
Dim btByteArray As Byte()
Dim a As New System.Text.ASCIIEncoding()
btByteArray = a.GetBytes(sInString)
ToBase64 = System.Convert.ToBase64String(btByteArray, 0, btByteArray.Length)
End Function
Private Function FromBase64(ByVal sBase64String As String) As String
Dim objUTF8 As New UTF8Encoding()
FromBase64 = objUTF8.GetString(Convert.FromBase64String(sBase64String))
End Function
Because one of the useful things about MVC is the SEO-friendly URLs, the code doesn’t convert to Base 64 unless it is necessary.
To use these functions, here is a brief code snippet:
Public Class HotelsController
Inherits System.Web.Mvc.Controller
Function SelectHotelList(ByVal City As String, _
ByVal Location As String)
oSearch = New With {.City = MyURLEncode(City), .Location = MyURLEncode(Location)}
Dim oDO As New RouteValueDictionary(oSearch)
Return RedirectToAction("List", "Hotels", oDO)
End Function
Function List(ByVal City As String, _
ByVal Location As String)
City = MyURLDecode(City)
Location = MyURLDecode(Location)
...
End Function
End Class


Kayak is one of the top travel meta-search engines on the web, and they have a free API which allows you to get flight and hotel information.