asp.net-mvc - MVC Web API,获取子项

标签 asp.net-mvc rest asp.net-web-api asp.net-4.5

我有一个包含两个表的数据库。每个城市与特定国家有关系的国家和城市。

在我的 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/

相关文章:

asp.net-mvc - JQUERY 调用 Controller 操作 : String Parameter truncated if containing 'space' character

asp.net-mvc - 何时使用RedirectToAction以及在哪里使用RedirectToRouteResult?

asp.net-mvc - 什么是一本好的中高级 ASP.NET MVC 2 书籍?

java - Jersey jarhell - v2.22.1,添加了所有依赖项

java - 检查 REST 响应是否包含空列表

c# - 将 IEnumerable 参数传递给 WebAPI

asp.net-mvc - 如何在 MVC Razor 中动态禁用 TextBox?

c# - 如何在运行时更改 Web API 的连接字符串

json - 从 HttpClient 向 webapi 提交文件和 Json 数据

java - Android-ReSTLet