我正在使用 asp net core mvc 并尝试开发Restfull应用。让我们说我有这样的模型:
internal class Album
{
public long Id { get; set; }
public string Name { get; set; }
public long ExecutorId { get; set; }
public virtual Executor Executor { get; set; }
}
internal class Executor
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Album> Albums { get; set; }
}
我有2个控制器,我这样写:
[ApiVersion("1")]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class ExecutorsController : Controller
{
[HttpGet("{id}", Name = "GetExecutor")]
public IActionResult GetById(long id)
{
//some code
}
[HttpGet(Name = "GetExecutors")]
public IActionResult GetAll()
{
//some code
}
}
[ApiVersion("1")]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class AlbumController : Controller
{
[HttpGet("{id}", Name = "GetAlbum")]
public IActionResult GetById(long id)
{
//some code
}
[HttpGet(Name = "GetAlbums")]
public IActionResult GetAll()
{
//some code
}
}
我可以致电&#34; http://localhost:48234/api/v1/Album/1&#34;并album
获取Id
,
我可以打电话给&#34; http://localhost:48234/api/v1/Album&#34;得到所有albums
。执行者也是如此。所以,我想要做的是能够albums
executorId
获得albums
并且我的路线看起来像
&#34; http://localhost:48234/api/v1/executors/1/albums&#34;,它将返回Id =1
的所有AlbumsController
执行者。问题是我想把这个动作放到[HttpGet]
[Route("executors/{executorId}/albums")]
public IActionResult GetAlbumsByExecutorId(long executorId)
{
return new ObjectResult(_service.GetAlbumsByExecutorId(executorId));
}
:
ControllerName
此代码工作得很好,但它会在ControllerName
(相册)开头。如何从我的路线中删除ExecutorsController
?或者也许我不应该这样做,只是把这个动作放到albums
?我决定这样做,因为如果操作返回AlbumsController
,它应该放在#define ASMSWAP32(dest_addr,data) __asm__ volatile ("stwbrx %0, 0, %1" : : "r" (data), "r" (dest_addr))
中。我错了吗?
答案 0 :(得分:2)
只需从控制器中的路径路径中删除[controller]并将其移至方法。
这样的事情:
[ApiVersion("1")]
[Route("api/v{api-version:apiVersion}/")]
public class AlbumController : Controller
{
[HttpGet("album/{id}", Name = "GetAlbum")]
public IActionResult GetById(long id)
{
//some code
}
[HttpGet("album", Name = "GetAlbums")]
public IActionResult GetAll()
{
//some code
}
[HttpGet]
[Route("executors/{executorId}/albums")]
public IActionResult GetAlbumsByExecutorId(long executorId)
{
return new ObjectResult(_service.GetAlbumsByExecutorId(executorId));
}
}
答案 1 :(得分:0)
如果您想获取相册,则应将操作方法放在AlbumController
。
我想以这种方式推荐你:
[HttpGet(Name = 'GetAlbumsByExecutorId')]
[Route("{executorId}/albums")]
public IActionResult GetAlbumsByExecutorId(long executorId)
{
return new ObjectResult(_service.GetAlbumsByExecutorId(executorId));
}