How to make more MapHttpRoutes for MVC 4 Api

☆樱花仙子☆ 提交于 2019-12-31 12:53:39

问题


I have 2 API routes for my API atm, but I want to add more, and the way I am doing it it seems to overwrite each other, so in the code I pasted, only the CreateUser route works.

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
        });
}

回答1:


I believe the pattern api/{controller}/{cUser} in "CreateUser" route is matching with rest of the controller actions because of its more generic pattern. Use specific controller name in the routes as "User" (api/User/{cUser}) and "Game" (api/Game/{playerId}). The more specific routes should be at the top and more generic at the bottom.

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
    }
);


来源:https://stackoverflow.com/questions/10766157/how-to-make-more-maphttproutes-for-mvc-4-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!