[ACCEPTED]-How to pass special characters so ASP.NET MVC can handle correctly query string data?-asp.net-mvc

Accepted answer
Score: 16

Ok, I confirmed that this is now a known issue 18 in ASP.NET Routing, unfortunately. The problem 17 is that deep in the bowels of routing, we 16 use Uri.EscapeString when escaping routing 15 parameters for the Uri. However, that method 14 does not escape the "#" character.

Note 13 that the # character (aka Octothorpe) is 12 technically the wrong character. C♯ the 11 language is actually a "C" followed 10 by a Sharp sign as in music: http://en.wikipedia.org/wiki/Sharp_(music)

If you used 9 the sharp sign, that could potentially solve 8 this problem. :P

Another solution, since 7 most people will want to use the octothorpe 6 is to write a custom route for this route 5 and after getting the virtual path path, encode 4 the # sign using HttpUtility.UrlEncode which 3 encodes # to %23.

As a follow-up, I wanted 2 to point you to this blog post which talks 1 about passing in other "invalid" characters. http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx

Score: 3

URL Encoding! Change the link so that it 2 encodes special characters.

Server.URLencode(strURL)

C# will become 1 "c%23".

Score: 3

Works on my machine. Here's what I did to 4 create the simplest possible example.

//Global.asax.cs

using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication4 {
  public class MvcApplication : System.Web.HttpApplication {
    public static void RegisterRoutes(RouteCollection routes) {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
        "Default",                        // Route name
        "{controller}/{action}/{id}",               // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
      );

      routes.MapRoute("Invoice-New-NewCustomer",
            "Invoice/New/Customer/New/{*name}",
            new { controller = "Customer", action = "NewInvoice" },
            new { name = @"[^\.]*" });
    }

    protected void Application_Start() {
      RegisterRoutes(RouteTable.Routes);
    }
  }
}

//HomeController.cs
using System.Web.Mvc;

namespace MvcApplication4.Controllers {
  [HandleError]
  public class HomeController : Controller {
    public ActionResult Index() {
      return RedirectToAction("NewInvoice", "Customer", new { name = "The C# Guy" });
    }
  }
}

//CustomerController.cs
using System.Web.Mvc;

namespace MvcApplication4.Controllers {
    public class CustomerController : Controller {
        public string NewInvoice(string name) {
            return name;
        }
    }
}

I then 3 started my app and navigated to /home/index. THe 2 redirect occurs and I saw "The C# Guy" in 1 my browser.

More Related questions