的WebAPI航线404时,有URL中的尾随空格的 [英] WebAPI route 404's when there is a trailing space in the URL

查看:88
本文介绍了的WebAPI航线404时,有URL中的尾随空格的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用默认的Web API路线

With the default web api route

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

和控制器

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

要请求API /测试/ 1

收益 1

如果由于某种原因,你发送一个请求到API /测试/ 1%20

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

路线404的。

现在这个例子可能看起来很傻,因为浏览器修剪尾随空格,但

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

对于像路线API / {控制器} / {ID} / {} extrastuff

1 将转换成 1%20 和要求空间将404上路线不被发现。

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

推荐答案

您的问题已无关的WebAPI本身,而是Asp.Net如何处理某些特定的URL。
而且Asp.Net在处理一个很偏执的方式这些URL,所以你需要告诉它<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.relaxedurltofilesystemmapping.aspx\">to放松。

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.

这行添加到你的web.config在的System.Web

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

同样在这样:

  • "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)

这篇关于的WebAPI航线404时,有URL中的尾随空格的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆