asp.net-mvcroutesasp.net-mvc-routingrouteconfig

Route containing <space> and forward slash


We had a route defined as

routes.MapRoute(
            name: "SearchFor",
            url: "Search/For/{text}",
            defaults: new
            {
                controller = "Search",
                action = "For",
                text = UrlParameter.Optional
            }

Following a new customer whose data happened to contain lots of forward slashes we had a problem with text such as item/1. To get around this the route was updated include a catch all as follows

routes.MapRoute(
            name: "SearchFor",
            url: "Search/For/{*text}",
            defaults: new
            {
                controller = "Search",
                action = "For",
                text = UrlParameter.Optional
            }

However this doesn't help if the text contains a leading space to the forward slash e.g. item /1 which causes IIS to return a 404 error.

Is it possible to get around this issue without encoding the text parameter in some manner?


Solution

  • Spaces (and most other special characters) must be URL encoded in order to be used in the path of URLs. However, this is a bad practice and should be avoided. See (Please) Stop Using Unsafe Characters in URLs.

    A better approach is to use the query string in combination with URL encoding for unsafe characters.

    routes.MapRoute(
            name: "SearchFor",
            url: "Search",
            defaults: new
            {
                controller = "Search",
                action = "For"
            }
    

    And used like...

    /search?text=Some%20Text
    

    Some firewalls and servers do not correctly interpret URL encoded information when it is part of the path, but query string information is more reliable. Not to mention the security concerns noted in the above article.

    Alternatively, you could design your URL to substitute unsafe characters for safe ones...

    /search/for/some-text
    

    ...but that will take more consideration to cover all of the special cases for your particular use case. Essentially, your application needs to be smart enough to convert the safe characters to and from the unsafe characters.

    But however you solve it, URLs are first and foremost made to be machine readable and you must take that into account when designing them.