如何在WebApi中实现多个Get方法

时间:2017-01-05 07:34:16

标签: asp.net-web-api

这里我试图实现多个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 }


            );  

2 个答案:

答案 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 });

另请参阅此 - Difference between "MapHttpRoute" and "MapRoute"?

答案 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 }
        );
    }
}

enter image description here

enter image description here