我有一个补救问题。在我们的代码库中,我看到了不同的API控制器,有时,开发人员使用以"/"开头的路由。而有时则不然。
据我所知,不管终点是否以"/"或者不是,它们都可以被同一个URI
发现https://localhost:123/nameofcontroller
示例c#代码:
[Route("/widgets/tools/calc")]
或(路线("小部件/工具/calc"]
重要吗?
编辑1
所以在一些额外的阅读之后,似乎我们正在使用属性路由…因为我们在控制器cs文件中定义路由,像这样:(如果我错了,请纠正我)
controller1.cs
[HttpGet]
[Route("/widgets/{widgetID}/report
controller2.cs
[HttpGet]
[Route("widgets/tools/calc
但我仍然试图理解以"/"开头的路线之间的区别是什么。和那些没有。
阅读下面代码中的注释:
namespace API.Controllers
{
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
/// <summary>
/// I prefer to use route attributes on controllers ...
/// ===========================================================================================
/// By default the mvc pattern looks so: {controller}/{action} + parameters if defined,
/// ===========================================================================================
/// </summary>
[ApiController, Route("/widgets")]
public class WidgetsController : ControllerBase
{
/// <summary>
/// ... and for specifying additional parameters using of http methods attributes ...
/// ===========================================================================================
/// when you use template without leading backslash it is appended to the controller route
/// and you have GET: /widgets/all instead of just GET: /widgets
/// ===========================================================================================
/// [HttpGet]
/// [Route("all")]
/// </summary>
[HttpGet("all")]
public ActionResult<IEnumerable<object>> Get()
{
return this.Ok(new [] { "w1", "w2", "etc." });
}
/// <summary>
/// ... but at the end both of them are valid ...
/// ===========================================================================================
/// when you use template with leading backslash the controller route is now OVERWRITTEN
/// and now looks so: GET: /all/criteria
/// ===========================================================================================
/// [HttpGet]
/// [Route("/all")]
/// </summary>
[HttpGet("/all/{filter}")]
public ActionResult<IEnumerable<object>> Get(string filter)
{
return this.Ok(new[] { "w1", "w2" });
}
/// <summary>
/// ===========================================================================================
/// it is helpfull for defining route parameters like bellow
/// here the route will looks like GET /widgets/123
/// so you can have multiple get methods with different parameters
/// ===========================================================================================
/// </summary>
[HttpGet("{widgetId}")]
public ActionResult<object> Get(int widgetId)
{
return this.Ok(new { widgetId });
}
}
}
…在不指定控制器路由的情况下,它对uri没有影响。通过指定控制器路由,uri将如下所示:
GET: /widgets/{widgetID}/report
GET: /controller2/widgets/tools/calc