Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC routes with special characters

I'm trying to support some legacy urls, and map them to controller actions. The URLs look like this:

/~Home+Office~Note+Pads.html

Here's my route:

routes.MapRoute(
    "LegacyCategory",
    "{path}.html",
    new { controller = "LegacyCI", action = "Index", }
);

Here's the (beginnings of) my controller to deal with them:

public class LegacyCIController : Controller {
    public ActionResult Index(string path) {
        if (path == "~Address+Labels") {
            return RedirectToAction("Display", "Category", new { id = "AddressLabels" });
        }       
        return RedirectToAction("Index", "Category"); 
    }
}

If I set a breakpoint in LegacyCIController, and I set my start page to XXX.html, the breakpoint hits (and fails the if) and life is good. But when I try to set the start page to ~Address+Labels.html, no breakpoint is hit, and Chrome just pukes and shows me a page that says "oops, this page appears to be broken".

I'm running this page through IIS 7 on my machine, not Visual Studio.

Is this URL so malformed that a regular MVC route can't even handle it, or am I doing something else wrong?

like image 509
Adam Rackis Avatar asked Apr 20 '12 18:04

Adam Rackis


People also ask

How do you handle special characters in MVC?

I think the url http://.../home/index?id=a%2fb will work. To generate this url you need to change your route: routes. MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Home", action = "Index" } );

Can we add constraints to the route in MVC?

Attribute Routing is introduced in MVC 5.0. We can also define parameter constraints by placing a constraint name after the parameter name separated by a colon. There are many builtin routing constraints available. We can also create custom routing constraints.

Can we have multiple routes in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.


1 Answers

By default IIS7 blocks URLs (error 404.11) with a + in the path, you can override this by turning on allowDoubleEscaping in web.config:

  <system.webServer>
    <security>
      <requestFiltering allowDoubleEscaping="true">
      </requestFiltering>
    </security>
  </system.webServer>

However, as explained on the IIS blog this option opens a potential security hole, so be a little careful while using it:

http://blogs.iis.net/thomad/archive/2007/12/17/iis7-rejecting-urls-containing.aspx

like image 154
pjumble Avatar answered Sep 30 '22 14:09

pjumble