14

我的 API atm 有 2 个 API 路由,但我想添加更多,而且我这样做的方式似乎相互覆盖,所以在我粘贴的代码中,只有CreateUser路由有效。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapHttpRoute(
        name: "CreateUser",
        routeTemplate: "api/{controller}/{cUser}",
        defaults: new
        {
            controller = "User",
            action = "CreateUser",
            cUser = RouteParameter.Optional
        });
    routes.MapHttpRoute(
        name: "AllGames",
        routeTemplate: "api/{controller}/{playerId}",
        defaults: new
        {
            controller = "Game",
            action = "GetAllGames",
            playerId = RouteParameter.Optional
        });
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional
        });
}
4

1 回答 1

19

我相信api/{controller}/{cUser}“CreateUser”路由中的模式与其他控制器操作匹配,因为它具有更通用的模式。在路由中使用特定的控制器名称作为“用户”(api/User/{cUser})和“游戏”(api/Game/{playerId})。更具体的路线应该在顶部,更通用的在底部。

routes.MapHttpRoute(
    name: "CreateUser",
    routeTemplate: "api/User/{cUser}",
    defaults: new
    {
        controller = "User",
        action = "CreateUser",
        cUser = RouteParameter.Optional
    }
);

routes.MapHttpRoute(
    name: "AllGames",
    routeTemplate: "api/Game/{playerId}",
    defaults: new
    {
        controller = "Game",
        action = "GetAllGames",
        playerId = RouteParameter.Optional
    }
);
于 2012-05-26T14:46:23.907 回答