MVC的Web API,得到子项目 [英] MVC Web API, get sub items

查看:162
本文介绍了MVC的Web API,得到子项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表的数据库。国家和城市,每个城市都有一个关系到国家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请求国家的列表,的http://例子.COM / API /国家来运行CountriesController。我可以通过 http://example.com/api/countries/1。

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.

如果我要为一个国家的所有城市的列表的REST查询URL应该是的http:/ /example.com/api/countries/1/cities ?而对于一个城市 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,得到子项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆