asp.net 核心控制器动作路由使用编码斜杠来确定路由(仅限 IIS)

asp.net core controller action route uses encoded slash to determine route (IIS only)

我有一个 asp.net 核心 2.2 mvc 操作方法,GET 它来自客户端 JavaScript 代码:

[Route("/search/{searchterm}")]
public IActionResult Search(string searchterm)
{
    // code
}

现在,当我导航到使用搜索字符串进行搜索时 abc/def 浏览器中的 uri 是 /search/abc%2Fdef 因为 / 被编码

不过我得到了一个 404,因为路由属性解码了斜杠并且 /search/abc/def 与我的路由不匹配。 我想要的是将 %2F 视为正常内容,因此搜索字符串在我的操作方法中是 abc/def

Funny(?) 事情是,这不会发生在我 运行 来自 VS2017(我猜是 运行s Kestrel)的本地机器上,但只发生在测试服务器上 运行在 IIS 上。

这是 IIS 的东西吗?或者负载均衡器正在做某事?

您可以使用星号表示 searchterm 可以包含斜线。这称为 catch-all parameter,看起来像这样:

[Route("/search/{**searchterm}")]
public IActionResult Search(string searchterm)
{
    // code
}

来自文档:

You can use an asterisk (*) or double asterisk (**) as a prefix to a route parameter to bind to the rest of the URI. These are called a catch-all parameters. For example, blog/{**slug} matches any URI that starts with /blog and has any value following it, which is assigned to the slug route value. Catch-all parameters can also match the empty string.

The catch-all parameter escapes the appropriate characters when the route is used to generate a URL, including path separator (/) characters. For example, the route foo/{*path} with route values { path = "my/path" } generates foo/my%2Fpath. Note the escaped forward slash. To round-trip path separator characters, use the ** route parameter prefix. The route foo/{**path} with { path = "my/path" } generates foo/my/path.