MVC4 WebApi路由与ActionNames不允许通用的"Get"
本文关键字:quot Get 路由 WebApi ActionNames 不允许 MVC4 | 更新日期: 2023-09-27 17:51:14
我一直有麻烦,试图能够有多个"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/
错误:"多个动作被发现匹配的请求"当我试图去/api/courses
通过为ApiControllerOnly
路由指定默认动作为"Get",我能够使/api/courses
工作。这适用于您的场景吗?
routes.MapHttpRoute(
name: "ApiControllerOnly",
routeTemplate: "api/{controller}",
defaults: new { action = "Get" }
);
编辑:
如果你在你的APIController中有额外的Put/Post/etc方法,你应该考虑在ApiControllerOnly
路由上使用HttpMethodConstraint
,并为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}"
);