ASP.NET Core Web API 路由的有效使用

ROUTING

在 .NET Core Web API 项目中,我们应该使用属性路由代替传统路由,这是因为属性路由可以帮助我们匹配路由参数名称与 Action 内的实际参数方法。另一个原因是路由参数的描述,对我们而言,一个名为 "ownerId" 的参数要比 "id" 更加具有可读性。

我们可以使用 [Route] 属性来在控制器的顶部进行标注:

[Route("api/[controller]")]
public class OwnerController : Controller
{
   [Route("{id}")]
   [HttpGet]
   public IActionResult GetOwnerById(Guid id)
   {
   }
}

  

还有另一种方式为控制器和操作创建路由规则:

[Route("api/owner")]
public class OwnerController : Controller
{
   [Route("{id}")]
   [HttpGet]
   public IActionResult GetOwnerById(Guid id)
   {
   }
}

  

对于这两种方式哪种会好一些存在分歧,但是我们经常建议采用第二种方式。这是我们一直在项目中采用的方式。

当我们谈论路由时,我们需要提到路由的命名规则。我们可以为我们的操作使用描述性名称,但对于 路由/节点,我们应该使用 NOUNS 而不是 VERBS。

一个较差的示例:

[Route("api/owner")]
public class OwnerController : Controller
{
   [HttpGet("getAllOwners")]
   public IActionResult GetAllOwners()
   {
   }
   [HttpGet("getOwnerById/{id}"]
   public IActionResult GetOwnerById(Guid id)
   {
   }
}

  

一个较好的示例:

[Route("api/owner")]
public class OwnerController : Controller
{
   [HttpGet]
   public IActionResult GetAllOwners()
   {
   }
   [HttpGet("{id}"]
   public IActionResult GetOwnerById(Guid id)
   {
   }
}

  

posted @ 2020-01-21 17:22  介尘(Heroy)  阅读(2012)  评论(0编辑  收藏  举报