MVC Web API, get sub items

浪尽此生 提交于 2019-12-22 17:39:06

问题


I have a database with two tables. Countries and Cities where each city has a relation to a spesific country.

In my ASP.Net Web API I can get a list of countries by a GET request to http://example.com/api/countries to run the CountriesController. And I can get details about a country by http://example.com/api/countries/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

How can I accomplish this in ASP.Net Web API?


回答1:


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" }
);

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 :)



来源:https://stackoverflow.com/questions/10555323/mvc-web-api-get-sub-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!