2

2つのテーブルを持つデータベースがあります。各都市が特定の国と関係がある国および都市。

ASP.Net Web APIでは、http://example.com/api/countriesへのGETリクエストによって国のリストを取得してCountriesControllerを実行できます。また、 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でこれをどのように達成できますか?

4

1 に答える 1

3

これはどうですか、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)
    {
    }
}

言うまでもなく、コントローラーの実装を少し改善したいと思うかもしれません:)

于 2012-05-12T04:27:03.717 に答える