假设我有以下类用于使用 EF 代码优先方法将数据存储在数据库中,并且需要通过 Web REST API(.NET core 2.0 restful API)使用这些类
public class Artist
{
public long ArtistId { get; set; }
public string Name { get; set; }
public ICollection<Song> Songs { get; set; }
}
public class Song
{
public long SongId { get; set; }
public long ArtistId { get; set; }
public string Name { get; set; }
public Artist Artist { get; set; }
}
另外,假设我有以下 RESTFUL API 控制器
[Produces("application/json")]
[Route("api/Artists")]
public class ArtistsController : Controller
{
private readonly ApiRepository repository;
// GET: api/Artists/1
[HttpGet("{id}")]
public object GetArtist([FromRoute] long id)
{
return repository.GetArtist(id) ?? NotFound();
}
// GET: api/Artists/1/Song/4
[HttpGet("How do I make this configuration?")]
public object GetSong([FromRoute] long artistId, long songId)
{
// Get the artist from the artistId
// Return the song corresponding to that artist
}
}
此时,我可以通过https://www.myserver/api/Artists/1
. 但是,我希望能够从艺术家 ID 接收歌曲。因此,我的问题如下:
GetSong([FromRoute] long ArtistId, long songId)
以获得类似于https://www.myserver/api/Artists/1/Songs/1
SongsController
? 我将如何配置此控制器以坚持上述路由?使路线成为 GET: api/Artists/1/Song/4
// GET: api/Artists/1/Song/4
[HttpGet("{artistId}/Song/{songId}")]
public object GetSong([FromRoute] long artistId, long songId)
{
// Get the artist from the artistId
// Return the song corresponding to that artist
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句