gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:47:03 26 4
gpt4 key购买 nike

我有一个包含两个表的数据库。每个城市都与特定国家/地区相关的国家和城市。

在我的 ASP.Net Web API 中,我可以通过向 http://example.com/api/countries 发出 GET 请求来获取国家/地区列表。运行国家 Controller 。我可以通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com