我有一个包含两个表的数据库。每个城市与特定国家有关系的国家和城市。
在我的 ASP.Net Web API 中,我可以通过向 http://example.com/api/countries 发送 GET 请求来获取国家/地区列表。运行 CountryController。我可以通过 http://example.com/api/countries/1 获取有关某个国家/地区的详细信息。
如果我想要一个国家/地区的所有城市的列表,REST 查询 URL 应为 http://example.com/api/countries/1/cities ?以及城市的详细信息 http://example.com/api/countries/1/cities/1
如何在 ASP.Net Web API 中实现此目的?
最佳答案
怎么样,在 global.asax.cs 中定义一个额外的 api 路由,如下所示:
routes.MapHttpRoute(
name: "CityDetail",
routeTemplate: "api/countries/{countryid}/cities/{cityid}",
defaults: new { controller = "Cities" }
);
然后定义一个新的 CitiesController,如下所示:
public class CitiesController : ApiController
{
// GET /api/values
public IEnumerable Get()
{
return new string[] { "value1", "value2" };
}
// GET /api/values/5
public string Get(int countryId, int cityid)
{
return "value";
}
// POST /api/values
public void Post(string value)
{
}
// PUT /api/values/5
public void Put(int countryId, int cityid, string value)
{
}
// DELETE /api/values/5
public void Delete(int countryId, int cityid)
{
}
}
不用说,您可能想稍微改进一下 Controller 的实现:)
关于asp.net-mvc - MVC Web API,获取子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10555323/