我有一個補救問題。在我們的代碼庫中,我看到了不同的 API 控制器,有時,開發人員使用以“/”開頭的路由,而其他時候則不是。
據我所知,無論端點是否以“/”開頭,它們都可以通過同一個 URI 發現
https://localhost:123/nameofcontroller
示例 C# 代碼:
[Route("/widgets/tools/calc")]
或 [Route("widgets/tools/calc")]
有關系嗎?
編輯 1
所以經過一些額外的閱讀之后,似乎我們正在使用屬性路由......因為我們在控制器cs檔案中定義了路由,如下所示:(如果我錯了,請糾正我)
控制器1.cs
[HttpGet]
[Route("/widgets/{widgetID}/report
控制器2.cs
[HttpGet]
[Route("widgets/tools/calc
但我仍在嘗試了解以“/”開頭的路線與不以“/”開頭的路線之間的差異。
uj5u.com熱心網友回復:
閱讀下面代碼中的注釋:
namespace API.Controllers
{
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
/// <summary>
/// I preffer 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 });
}
}
}
... whitout 指定控制器路由它對 uri 沒有影響。指定控制器路由后,uris 將如下所示:
GET: /widgets/{widgetID}/report
GET: /controller2/widgets/tools/calc
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487064.html
