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

编程入门 行业动态 更新时间:2024-10-27 21:23:52
本文介绍了URL 中有尾随空格时的 WebAPI 路由 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用默认的 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:

  • 放置 Con(COM1、LPT1、NUL 等)回到您的网址中

也在 SO 上:

  • "找不到资源.";有点"时出错在网址的末尾
  • 网址以 %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

本文发布于:2023-11-13 21:35:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585381.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   路由   空格   URL   WebAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!