带斜杠“/"的路由参数在网址中 [英] Route parameter with slash "/" in URL
问题描述
我知道您可以在路由属性中应用通配符以允许 /
例如日期输入:
I know you can apply a wildcard in the route attribute to allow /
such as date input for example:
[Route("orders/{*orderdate}")]
通配符的问题只适用于URI中的最后一个参数.如果想拥有以下 URI,我该如何解决这个问题:
The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI:
[Route("orders/{orderdate}/customers")]
更新:
我知道通过重构代码来解决问题的方法很少,所以请不要提供类似以下的解决方案:
I know there are few options to solve the issue by refactoring the code so please do not offer a solution something like:
- 将路由模板更改为
[Route("orders/customers/{orderdate}")]
- 将日期更改为不同的格式(例如
"dd-mm-yyyy"
)
推荐答案
@bet.. 我认为 genericUriParserOptions
不再适用于 .net 4.5 或更高版本..
@bet.. I think the genericUriParserOptions
is no longer applicable to .net 4.5 or later..
另外,正如 @JotaBe 所建议的,您可能需要正确解码 url 请求.在大多数情况下,%2F
将自动转换为斜线 '/'
.因此,如果您需要对其进行转义,则首先需要对 '%'
字符进行解码.因此您的 URL: 将类似于:www.domain.com/api/订单/23%252F06%252F2015/customers
Also as suggested by @JotaBe, you might need to correctly decode the url request. In most case the %2F
will be automatically translated to a slash '/'
. So if you need to escape it you will need to decode the '%'
char in the first place.. so your URL: will look something like: www.domain.com/api/orders/23%252F06%252F2015/customers
注意字符 '%252F'
将被转换为实际的 '%2F'
Notice the characters '%252F'
will be translated to the actual '%2F'
编辑
好的,这是完整的解决方案(已尝试并为我工作):
Ok here is the complete solution (Tried it and working for me):
假设您有一个像这样的 API 端点:
Assuming you have an API endpoint like so:
[Route("orders/{date}/customers")]
public HttpResponseMessage Get(string date)
{
}
在 web.config 中,您需要将 requestPathInvalidCharacters
设置为空,这告诉 asp.net 允许所有请求
In the web.config you will need to set the requestPathInvalidCharacters
to empty which tells the asp.net to allow all request
<system.web>
<httpRuntime targetFramework="4.5" requestPathInvalidCharacters=""/>
</system.web>
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
</system.webServer>
当客户端向 API 发送请求时,您需要确保像这样转义 '%'
:
www.domain.com/api/orders/23%252F06%252F2015/customers
www.domain.com/api/orders/23%252F06%252F2015/customers
然后您需要对请求进行解码
You then need to decode the request
[Route("orders/{date}/customers")]
public HttpResponseMessage Get(string date)
{
DateTime actualDate = DateTime.Parse(System.Net.WebUtility.UrlDecode(date)); // date is 23/06/2015
}
这篇关于带斜杠“/"的路由参数在网址中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!