您可以使用以下代码示例来解决ASP.NET Core Web API不返回子项列表的问题:
[Route("api/[controller]")]
[ApiController]
public class ParentController : ControllerBase
{
[HttpGet("{parentId}/child")]
public ActionResult> GetChildItems(int parentId)
{
// 从数据库或其他数据源获取子项列表
List childItems = GetChildItemsFromDataSource(parentId);
// 返回子项列表
return childItems;
}
private List GetChildItemsFromDataSource(int parentId)
{
// 实现从数据库或其他数据源获取子项列表的逻辑
// 返回子项列表
}
}
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddControllers();
services.AddRouting(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
// ...
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ...
// 初始化数据库上下文(示例为Entity Framework Core)
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
// ...
}
// ...
}
这样,当您发送GET请求到/api/parent/{parentId}/child
时,将返回该父项的子项列表。请确保替换{parentId}
为实际的父项ID。