这里我试图实现多个Get方法,但浏览器会出现错误Multiple actions were found that match the request
。为什么会这样?
在Api控制器中,我添加了两个方法:1。GetEmployee 2. HelloDept如果我注释掉其中一个,它工作正常。
public class TrailController : ApiController
{
private IProduct Repo = new Product();
[HttpGet]
public IEnumerable<Employee> GetEmployee()
{
var x = Repo.GetEmp();
return x;
}
[HttpGet]
public IEnumerable<Department> HelloDept()
{
var x = Repo.GetDept();
return x;
}
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{api}/{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new {id = RouteParameter.Optional }
);
答案 0 :(得分:1)
在RouteConfig.cs中更改您的代码。
发件人强>:
routes.MapRoute(
name: "Default",
url: "{api}/{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new {id = RouteParameter.Optional }
);
要强>:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
答案 1 :(得分:0)
在您的WebApiConfig.cs中更改
`api/{controller}/{id}`
与
`api/{controller}/{action}/{id}`.
然后调用类似 -
的操作http://localhost:port/api/controller/HelloDept
http://localhost:port/api/controller/GetEmployee
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}