gpt4 book ai didi

c# - 带有 ActionNames 的 MVC4 WebApi 路由不允许通用 "Get"

转载 作者:行者123 更新时间:2023-11-30 21:01:20 41 4
gpt4 key购买 nike

我一直无法尝试拥有多个“Get”方法,同时还具有默认值/api/{controller}。这是一个带有伪代码的示例(是的,我知道它会返回完全相同的代码)。

错误:当我尝试转到 /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/上的类(class)

最佳答案

Error: "Multiple actions were found that match the request" when I try to go to /api/courses

通过将 ApiControllerOnly 路由的默认操作指定为“Get”,我能够让 /api/courses 工作。这是否适用于您的场景?

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

编辑:

如果您的 APIController 中有额外的 Put/Post/etc 方法,您应该考虑在 ApiControllerOnly 路由上使用 HttpMethodConstraint 并添加另一条路由(即 ApiControllerOnly2 ) 用于 Put/Post/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}"
);

关于c# - 带有 ActionNames 的 MVC4 WebApi 路由不允许通用 "Get",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272569/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com