【问题标题】:Remove Route from HttpRouteCollection从 HttpRouteCollection 中删除路由
【发布时间】:2023-03-29 11:28:02
【问题描述】:

我正在使用 WebAPI 2.0 中包含的属性路由,但无法弄清楚如何根据某些条件删除路由。我使用MapHttpAttributeRoutes 映射所有路线,然后我想使用下一行代码删除特定路线。

        // enable attribute routing support
        httpConfiguration.MapHttpAttributeRoutes();

        // expose the flag routes only if required
        if (DisableFlagEndpoint)
        {
            httpConfiguration.Routes.Remove(FlagsController.RouteName);
        }

但这会引发NotSupportedException。如何删除一条路线?如果没有,还有其他方法可以实现吗?

【问题讨论】:

  • ineresting..您需要执行此操作的具体场景是什么?
  • 我想禁用/删除每个环境的路由。例如,测试路由入口只需要在开发机器上,所以我只想在那里启用它并在所有其他配置中禁用它。我猜我将不得不编写一个快速过滤器来实现这一点......

标签: c# asp.net-web-api-routing asp.net-web-api2


【解决方案1】:

看起来 WebAPI 2.1 引入了使用 IgnoreRoute() 执行此操作的功能。 http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#ignoreroute

// disable the flag routes if required
if (DisableFlagEndpoint)
{
    httpConfiguration.Routes.IgnoreRoute("Flags", "api/flags/{*paths}");
}

// enable attribute routing support
httpConfiguration.MapHttpAttributeRoutes();

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2018-04-27
    • 2017-05-12
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2020-01-16
    • 2021-12-27
    相关资源
    最近更新 更多