問題描述
使用默認的 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/test/1'
返回 1
如果由于某種原因您向 'api/test/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/{controller}/{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,因此您需要告訴它 放松.
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.
在 system.web
下將此行添加到您的 web.config:
Add this line to your web.config under system.web
:
<httpRuntime relaxedUrlToFileSystemMapping="true" />
您可以閱讀有關此主題的更多信息:
You can read more about this topic:
- 把騙局(COM1,LPT1,NUL 等)返回您的網址
同樣在 SO:
- 找不到資源."有點"時出現錯誤;在網址的末尾
- URL 以 %20 結尾的問題(它描述了不同的上下文,所以我不認為這是一個真正的重復)
- "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)
這篇關于當 URL 中有尾隨空格時,WebAPI 路由 404的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!