【问题标题】:asp.net mvc routing catch /{sometoken}asp.net mvc 路由捕获 /{sometoken}
【发布时间】:2019-01-20 21:32:20
【问题描述】:

http://www.example.com/ 有一个网站,应该回复 http://www.example.com/{sometoken} 。其中 {sometoken} 是长度为 6 的字符串。

如何编写 routes.MapRoute 以将 {sometoken} 的所有请求映射到“Controller1/GetIdAction?sometoken={sometoken}”。

这就是我尝试的方法,但没有成功,我做错了什么?

 routes.MapRoute(
                "TokenRoute",
                "{someToken}",
                new { controller = "Controller1", action = "GetIdAction" },
                new { someToken = "^[a-f0-9]{6}$" }
                );

【问题讨论】:

  • 如果您将其作为查询参数 ("?sometoken=foobar") 传递,则无需在路由中明确声明。
  • 对于带有查询字符串的 URL,无需使用 MapRoute(仅适用于带有斜杠的 URL)。将带有查询字符串的 URL 转换为带有斜杠的 URL 的机制称为 URL 重写(通常在 web.config 或 IIS 中配置)。
  • 谢谢@TetsuyaYamamoto。它与 web.config 一起工作。我没有意识到这一点。很好的解决方案。 :)

标签: c# asp.net .net asp.net-mvc routing


【解决方案1】:

这是 URL 重写,应该在 web.config 中配置。

<system.webServer>
 <rewrite>
    <rules>
      <rule name="someToken">
        <match ignoreCase="false" url="^([a-f0-9]{6})$" />
        <action type="Rewrite" url="Controller1/GetIdAction?someToken={R:1}" />      
      </rule>
    </rules>
  </rewrite>
</system.webServer>

https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module

感谢@TetsuyaYamamoto 的解决方案。

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 2011-04-29
    • 2016-07-09
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多