.NET Core 2 API 属性路由配置

用户10214452

假设我有以下类用于使用 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 接收歌曲。因此,我的问题如下:

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

使路线成为 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章