REST APIs的HttpVerbAttribute路由,Name有什么用属性

HttpVerbAttribute routing for REST APIs, what is the use of Name property

虽然我的 api controllers/actions 依赖基于 http 动词的属性路由,但我们可以使用如下内容:

[HttpGet("info/{id?}", Name = nameof(GetSomeInfo))]
public ActionResult<string> GetSomeInfo(string id, string lastName)
{
   return Ok(id + " Prerak " + lastName);
}

提琴手中的调用如下所示:

GET /WeatherForecast/info/23?lastName=myLastName

但我不确定我们在httpGetAttribute中设置的名称属性有什么用,如下所示:

[HttpGet("info/{id?}", Name = nameof(GetSomeInfo))]

我正在阅读此文档https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.httpgetattribute?view=aspnetcore-5.0

但是,它只是说如下,我很困惑有什么用,如果我们在这里设置的名称在url代中不显示,则总是形成url使用路线模板,例如"info/{id?}"

Gets the route name. The route name can be used to generate a link using a specific route, instead of relying on selection of a route based on the given set of route values.

(Inherited from HttpMethodAttribute)

拜托,我需要帮助来理解这一点,或者请指点我正确的资源。

TIA

当您需要为某个动作生成 link 时,请说出您的 GetSomeInfo 端点,您会怎么做?

您可以使用字符串插值手动生成它

var url = $"/info/{myId}";

虽然这行得通,但如果您将 [HttpGet("info/{id?}")] 更改为其他内容会发生什么,您是否对使用它的所有地方进行了更改?或者如果每个请求动态更改(取决于域、语言等)怎么办?

为了解决这个问题,您可以选择为您的操作命名,然后在构建 link:

时引用它

在控制器/中间件/Razor 页面中,您可以注入一个 LinkGenerator 实例:

var links = context.RequestServices.GetRequiredService<LinkGenerator>();
var href = links.GetUriByName(
    HttpContext,
    nameof(MyController.GetSomeInfo), // this gives you "GetSomeInfo"
    new { id = 123 }
);

或者在 Razor 模板中,您可以使用 <a asp-route"..." /> 帮助程序标记。

<a asp-route="GetSomeInfo" asp-route-id="123">Get Info</a>

此外,它会填充该操作的 OpenAPI operationId 元数据,这有助于客户端生成代码以使用您提供的名称访问您的端点,而不是操作的名称(这可能并不表明它实际上是什么确实如此,就像 GetSomeInfo).

的情况一样

From the docs:

Route names can be used to generate a URL based on a specific route. Route names:

  • Have no impact on the URL matching behavior of routing.
  • Are only used for URL generation. Route names must be unique application-wide.

Contrast the preceding code with the conventional default route, which defines the id parameter as optional ({id?}). The ability to precisely specify APIs has advantages, such as allowing /products and /products/5 to be dispatched to different actions.

参考: