具有操作名称的MVC4 Web Api路由不允许通用“获取”

时间:2013-01-11 06:00:30

标签: c# asp.net-mvc-4 asp.net-web-api

我一直无法尝试使用多个“Get”方法,同时还有默认的/ api / {controller}。这是一个使用虚拟代码的示例(是的,我意识到它将返回完全相同的内容)。

错误:"Multiple actions were found that match the request"当我尝试转到/api/courses

转到/api/courses/all工作正常,/api/courses/3

也一样
// GET api/courses
public IEnumerable<Courses> Get()
{
    return Db.Courses.OrderBy(x => x.Name);
}

// GET api/courses/all
[ActionName("all")]
public IEnumerable<Courses> GetAll()
{
    return Db.Courses.OrderBy(x => x.Name);
}

// GET api/courses/id
[ActionName("all")]
public Courses Get(int id)
{
    return Db.Courses.Where(x => x.id == id);
}

RouteConfig看起来像:

routes.MapHttpRoute(
       "ApiControllerOnly",
       "api/{controller}"
);

// Allow for numeric Ids to be passed in
routes.MapHttpRoute(
       "ApiControllerAndIntegerId",
       "api/{controller}/{id}",
       null,
       new { id = @"^\d+$" }
);

routes.MapHttpRoute(
       "ApiControllerAction",
       "api/{controller}/{action}"
);

我希望能够做的是致电:

/api/courses - returns Get()
/api/courses/all - returns GetAll()
/api/courses/3 - returns Get(id = 3)

编辑:

它还需要允许Put,Post等工作,例如Putting关于/ api / courses /

的课程

1 个答案:

答案 0 :(得分:4)

  

错误:当我尝试转到/ api / courses时,“找到了与请求匹配的多个操作”

通过为ApiControllerOnly路由指定默认操作“获取”,我可以让/api/courses工作。这适用于您的场景吗?

        routes.MapHttpRoute(
            name: "ApiControllerOnly",
            routeTemplate: "api/{controller}",
            defaults: new { action = "Get" }
        );

编辑:

如果您在APIController中有其他Put / Post / etc方法,则应考虑在HttpMethodConstraint路由上使用ApiControllerOnly并为Put /添加另一个路由(即ApiControllerOnly2)发布/ etc方法:

        config.Routes.MapHttpRoute(
            name: "ApiControllerOnly",
            routeTemplate: "api/{controller}",
            defaults: new { action = @"Get" },
            constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
        );

        config.Routes.MapHttpRoute(
            name: "ApiControllerOnly2",
            routeTemplate: "api/{controller}"
        );
        config.Routes.MapHttpRoute(
            name: "ApiControllerAndIntegerId",
            routeTemplate: "api/{controller}/{id}",
            defaults: null,
            constraints: new { id = @"^\d+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiControllerAction",
            routeTemplate: "api/{controller}/{action}"
        );