asp.net-mvc – 如何使更多MapHttpRoutes为MVC 4 Api

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何使更多MapHttpRoutes为MVC 4 Api前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的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
        });
}

解决方法

我相信“CreateUser”路由中的模式api / {controller} / {cUser}与其他控制器操作相匹配,因为它更通用的模式.在路由中使用特定的控制器名称为“User”(api / User / {cUser})和“Game”(api / Game / {playerId}).更具体的路线应该在顶部,更通用的底部.
routes.MapHttpRoute(
    name: "CreateUser",routeTemplate: "api/User/{cUser}",defaults: new
    {
        controller = "User",cUser = RouteParameter.Optional
    }
);

routes.MapHttpRoute(
    name: "AllGames",routeTemplate: "api/Game/{playerId}",defaults: new
    {
        controller = "Game",playerId = RouteParameter.Optional
    }
);

猜你在找的asp.Net相关文章