WebApi 函数调用冲突,忽略函数名

WebApi conflict calling to functions, it's ignoring the function names

我创建了一个简单的 ApiController 有 3 个函数。

我有 2 个场景,如果您能给我一个正确的解释,我将不胜感激。

Api Class:

public class PersonController : ApiController { 私人人物[] listPerson;

    public PersonController() {
        listPerson = new Person[3];
        listPerson[0] = new Person { 
            id = 1,
            firstName = "test",
            lastName = "test",
            email = "test@gmail.com",
            age = 26
        };
        listPerson[1] = new Person
        {
            id = 2,
            firstName = "test",
            lastName = "test",
            email = "test@gmail.com",
            age = 26
        };
        listPerson[2] = new Person
        {
            id = 3,
            firstName = "test",
            lastName = "test",
            email = "test@gmail.com",
            age = 26
        };
    }

    public Person GetById(int id) {
        try
        {
            var person = this.listPerson.Where(p => p.id == id).FirstOrDefault();
            if (person != null)
            {
                return person;
            }
            else {
                throw new InvalidOperationException();
            }
        }
        catch (Exception) {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }

    public Person[] Get()
    {
        try
        {
            if (this.listPerson != null)
            {
                return this.listPerson;
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        catch (Exception)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }

    public Person GetFirst()
    {
        try
        {
            if (this.listPerson != null)
            {
                return this.listPerson.Where(x=>x.Equals(1)).FirstOrDefault();
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        catch (Exception)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }
}

网络Api配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

好像ApiController只识别get和get?id,所以有人能解释一下为什么以及如何解决这个问题吗?

谢谢

自定义方法命名为 asp.net web api.

路由配置默认遵循RESTful GET,POST,PUT,Delete的约定。

Custom method names in ASP.NET Web API

完成这个 post 它会解决您的问题。

应该可以使用下面的代码,只需添加{action}

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { action = "get", id = RouteParameter.Optional }
);