You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让LinkGenerator生成符合REST规范的路径式URL?

解决REST风格URL生成问题

要生成https://localhost:7157/api/Books/{id}这种符合REST规范的URL,核心问题是路由模板未将id定义为路径参数,具体修改步骤如下:

1. 修改路由属性

把原接口的路由模板改成包含id路径占位符的形式,两种写法任选其一即可:

写法一(合并HttpGet与路由定义)

[HttpGet("{id}", Name = "GetBook")]
public ActionResult GetBook(Guid id)
{
    return Ok(new Book
    {
        Id = Guid.NewGuid(),
        Title = "The Grass is Always Greener",
        Author = " Jeffrey Archer",
        Description = "This ingenious tale examines the ambitions and petty jealousies of the staff at Critchley's Bank. From the doorman to the personnel manager, to Sir William, the bank's sorrowful chairman. Archer knits a panoply of characters with deft narrative skill in a story which is as revealing as it is observant. Taken from his anthology To Cut a Long Story Short, his other short story anthologies include A Quiver Full of Arrows, Twelve Red Herrings and A Twist in the Tale.",
        ISBN = "1-86092-049-7",
        Links = new Links
        {
            GET = _linkGenerator.GetUriByName(this.HttpContext, nameof(GetBook), new { id })
        }
    });
}

写法二(保留独立Route属性)

[HttpGet]
[Route("{id}", Name = "GetBook")]
public ActionResult GetBook(Guid id)
{
    // 方法内容与原代码一致即可
}

2. 原理说明

原路由模板为空字符串,接口路径仅为/api/Books,id参数只能通过查询字符串传递。添加{id}占位符后,ASP.NET Core会将id识别为URL路径的一部分,LinkGenerator.GetUriByName会依据这个路由模板,自动把传入的id值填充到路径中,从而生成符合REST规范的URL。

3. 修改后效果

重新运行项目后,生成的URL会变成:

https://localhost:7157/api/Books/00000000-0000-0000-0000-000000000000

内容的提问来源于stack exchange,提问作者kbd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:04:58