Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI route 404's when there is a trailing space in the URL

With the default web api route

config.Routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new
                      {
                          id = RouteParameter.Optional
                      }
            );

and a controller

public class TestController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, id);
    }
}

A request to 'api/test/1'

returns 1

If for some reason you send a request to 'api/test/1%20'

the route 404's.

Now this example may seem silly since browsers trim trailing spaces, but

for a route like 'api/{controller}/{id}/{extrastuff}'

the space in '1 ' would convert to '1%20' and the request will 404 on the route not being found.

like image 758
Steve Avatar asked Nov 15 '12 21:11

Steve


2 Answers

Your issue has nothing to do with WebAPI itself but how Asp.Net handles some specific urls. And Asp.Net handles these urls in a very paranoid way, so you need to tell it to relax.

Add this line to your web.config under system.web:

<httpRuntime relaxedUrlToFileSystemMapping="true" />

You can read more about this topic:

  • Putting the Con (COM1, LPT1, NUL, etc.) Back in your URLs

Also on SO:

  • "The resource cannot be found." error when there is a "dot" at the end of the url
  • Problem with a URL that ends with %20 (it describes a different context so I don't think that this is a real duplicate)
like image 79
nemesv Avatar answered Oct 20 '22 16:10

nemesv


Add this to handlers

      <add name="ExtensionlessUrlHandler-Integrated-4.0-ForApi"
     path="api/*"
     verb="*"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
like image 1
Toolkit Avatar answered Oct 20 '22 15:10

Toolkit