11

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.

4

2 回答 2

36

您的问题与 WebAPI 本身无关,而是 Asp.Net 如何处理某些特定的 url。而 Asp.Net 以非常偏执的方式处理这些 url,所以你需要告诉它放松

将此行添加到您的 web.config 下system.web

<httpRuntime relaxedUrlToFileSystemMapping="true" />

您可以阅读有关此主题的更多信息:

同样在SO上:

于 2012-11-15T21:47:40.043 回答
1

将此添加到处理程序

      <add name="ExtensionlessUrlHandler-Integrated-4.0-ForApi"
     path="api/*"
     verb="*"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
于 2016-12-15T12:57:12.893 回答