.NET Core 2 API 属性路由配置

.NET Core 2 API attribute routing configuration

假设我有以下 class 用于使用 EF 代码优先方法将数据存储在数据库中并且需要通过 Web REST API(.NET 核心 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 接收歌曲。因此,我的问题如下:

  1. 如何在方法上使用属性路由配置 GetSong([FromRoute] long ArtistId, long songId) 以获得类似于 https://www.myserver/api/Artists/1/Songs/1
  2. 的路线
  3. 我觉得,如果我使用上述方法,我将被迫将所有 API 方法塞进一个控制器中。这可能会导致一个大控制器 class。我应该把与歌曲相关的调用放在 SongsController 中吗?我将如何配置此控制器以坚持上述路由?
  4. 有没有其他推荐的方法(模式)来解决这个问题?

将路线设置为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
}