问题描述
我有两个表的数据库。国家和城市,每个城市都有一个关系到国家spesific。
I have a database with two tables. Countries and Cities where each city has a relation to a spesific country.
在我的ASP.Net的Web API,我可以通过一个GET请求国家的列表,来运行CountriesController。我可以通过?而对于一个城市 http://example.com/api/countries/1/cities/ 1
If I want a list of all cities for a country the REST query URL should be http://example.com/api/countries/1/cities? And details for a City http://example.com/api/countries/1/cities/1
我怎样才能做到这一点在ASP.Net的Web API?
How can I accomplish this in ASP.Net Web API?
推荐答案
这个怎么样,在规定的global.asax.cs像这样一个附加的API的路线:
How about this, in global.asax.cs define an additional api route like so:
routes.MapHttpRoute(
name: "CityDetail",
routeTemplate: "api/countries/{countryid}/cities/{cityid}",
defaults: new { controller = "Cities" }
);
然后定义一个新的CitiesController像这样:
Then define a new CitiesController like so:
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)
{
}
}
不用说,你可能想提高控制器实现了一下:)
Needless to say you might want to improve the controller implementation a bit :)
这篇关于MVC的Web API,得到子项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!