如何在ASP.net WebAPI项目中添加和调用其他Get方法

时间:2014-09-26 10:09:01

标签: c# asp.net .net asp.net-mvc asp.net-web-api

我的WebAPI项目包含以下控制器。

public class StateController : ApiController
    {
        // GET: api/State
        public IEnumerable<State> Get()
        {
            return new StateRepository().GetAll();
        }


       ////////////// How to call this method from client code ?  ////////////// 
        public IEnumerable<State> GetAllByCountryId(int id)
        {
            return new StateRepository().GetAllStatesByCountryId((short)id);
        }

        // GET: api/State/5
        public State Get(int id)
        {
            return new StateRepository().Get(id);
        }

        // POST: api/State
        public void Post([FromBody]State state)
        {
            new StateRepository().Create(state);

        }

        // PUT: api/State/5
        public void Put(int id, [FromBody]State state)
        {
            new StateRepository().Update(state);
        }

        // DELETE: api/State/5
        public void Delete(int id)
        {
            new StateRepository().Delete(id);
        }
    }

2 个答案:

答案 0 :(得分:0)

我通过将以下代码添加到WebAPIConfig.cs

来完成此操作
// Controller Only
// To handle routes like `/api/State`
config.Routes.MapHttpRoute(
    name: "ControllerOnly",
    routeTemplate: "api/{controller}"
);

// Controller with ID
config.Routes.MapHttpRoute(
    name: "ControllerAndId",
    routeTemplate: "api/{controller}/{id}",
    defaults: null,
    constraints: new { id = @"^\d+$" } // Only integers 
);

// Controllers with Actions and Id
config.Routes.MapHttpRoute(
    name: "ControllerAndActionAndId",
    routeTemplate: "api/{controller}/{action}/{id}"
);

答案 1 :(得分:0)

您是否更改了以下路线配置? ID也是必需的。

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