如何在ASP.net WebAPI项目中添加和调用额外的Get方法
本文关键字:调用 方法 Get 添加 ASP net 项目 WebAPI | 更新日期: 2023-09-27 18:24:32
我的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);
}
}
您是否更改了以下路由配置?Id在同一个中是必需的。
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我通过将以下代码添加到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}"
);