【问题标题】:How to add and call additional Get Method in ASP.net WebAPI Project如何在 ASP.net WebAPI 项目中添加和调用额外的 Get 方法
【发布时间】:2014-09-26 10:09:00
【问题描述】:

我的 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);
        }
    }

【问题讨论】:

  • 你想从IEnumerable&lt;State&gt; Get()方法调用这个方法-GetAllByCountryId(int id)对吗???

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


【解决方案1】:

您是否更改了如下路线配置? id也是一样的。

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

【讨论】:

    【解决方案2】:

    我通过将以下代码添加到 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}"
    );
    

    【讨论】:

    • 请通过其他编辑来编辑您的原始问题,而不是将它们作为答案发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2019-01-17
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多