2

我一直在尝试能够拥有多个“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/ 上的课程

4

1 回答 1

4

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

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

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

编辑:

如果您的 APIController 中有额外的 Put/Post/etc 方法,则应考虑HttpMethodConstraintApiControllerOnly路由上使用并为 Put/Post/etc 方法添加另一个路由(即ApiControllerOnly2):

        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}"
        );
于 2013-01-11T07:27:22.240 回答