config.Routes.MapHttpRoute 正在覆盖 Web API 2.0

config.Routes.MapHttpRoute getting overridden Web API 2.0

为什么我的 AccessManagement 路由模板在 MVC Web 中不可见 API 2.

// Web API routes
//config.MapHttpAttributeRoutes();

//Just exclude the users controllers from need to provide valid token, so they could authenticate
config.Routes.MapHttpRoute(
    name: "Authentication",
    routeTemplate: "AccessManagement/",
    defaults: new { controller = "AccessManagement" }
);

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: null,
    //Create and instance of TokenInspector setting the default inner handler
    handler: new TokenInspector() { 
        InnerHandler = new HttpControllerDispatcher(config) 
    }
);

我需要通过确保 header 中存在令牌来保护我所有具有模板 api/{controller}/{action} 的路由,并且只有一条路由在没有 header 的情况下公开,即 AccessManagement/

实际上,您的第一条路线只会匹配 URL "/AccessManagement",不会接受任何其他路线。

因此,给定 URL http://localhost:49531/AccessManagement/Authenticate 并假设您的 AccessManagement 控制器有一个名为 Authenticate 的操作,此路由将匹配 URL:

config.Routes.MapHttpRoute(
    name: "Authentication",
    routeTemplate: "AccessManagement/{action}",
    defaults: new { controller = "AccessManagement" }
);