简体   繁体   English

当URL中有尾随空格时,WebAPI路由404

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

With the default web api route 使用默认的Web api路由

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' 请求'api/test/1'

returns 1 返回1

If for some reason you send a request to 'api/test/1%20' 如果由于某种原因你向'api/test/1%20'发送请求

the route 404's. 路线404的。

Now this example may seem silly since browsers trim trailing spaces, but 现在这个例子看起来很愚蠢,因为浏览器会修剪尾随空格,但是

for a route like 'api/{controller}/{id}/{extrastuff}' 对于像'api/{controller}/{id}/{extrastuff}'这样的路线

the space in '1 ' would convert to '1%20' and the request will 404 on the route not being found. '1 '的空格将转换为'1%20'并且未找到路径上的请求将为404。

Your issue has nothing to do with WebAPI itself but how Asp.Net handles some specific urls. 您的问题与WebAPI本身无关,但Asp.Net如何处理某些特定网址。 And Asp.Net handles these urls in a very paranoid way, so you need to tell it to relax . Asp.Net以非常偏执的方式处理这些网址,因此您需要告诉它放松

Add this line to your web.config under system.web : 将此行添加到system.web下的web.config:

<httpRuntime relaxedUrlToFileSystemMapping="true" />

You can read more about this topic: 您可以阅读有关此主题的更多信息:

Also on SO: 同样在SO:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM