c# - 在 ASP.NET Core 7 WebApi 中使用 RouteGroupBuilder 时如何获取路由组前缀

标签 c# .net asp.net-core asp.net-web-api

.NET v7 框架引入了路由组的概念,根据路径中的公共(public)前缀将映射的端点分组在一起:

app.MapGroup("/public/todos").MapTodosApi();

现在,为了返回 Created 响应(即 POST 请求)的绝对路径,我需要服务内的路由路径前缀。这个用例甚至被讨论过 in the official documentation :

Instead of using relative addresses for the Location header in the 201 Created result, it’s also possible to use GroupRouteBuilder.GroupPrefix to construct a root-relative address

但是,GroupRouteBuilder 类不存在。只有一个RouteGroupBuilder ,但它的实例没有成员GroupPrefix。有什么建议如何实际获取前缀吗?

最佳答案

那个document您链接 - 尽管是预览版 - 提到:

use GetPathByRouteValues or GetUriByRouteValues with a routeName for even more options.

关于链接生成的官方是here .
它展示了如何注入(inject)和使用 LinkGenerator (还包含上面提到的 2 个方法)与这样的命名路由相结合。

Endpoints can be given names in order to generate URLs to the endpoint. Using a named endpoint avoids having to hard code paths in an app

将此应用于您所引用的示例;
为检索 Todo 项目的路由指定名称, 并在生成创建的 URL 时使用该 URL。


var group = app.MapGroup("todos");
group
    .MapGet("/{id}", (int id) =>
    {                
        // ...
        return new Todo { Id = id };
    })
    .WithName("GetToDo");

group
    .MapPost("/", (Todo todo, LinkGenerator linkGenerator) =>
    {
        // ...
        var url = linkGenerator.GetPathByName("GetToDo", new { id = todo.Id });
        return TypedResults.Created(url, todo);
    });

如果 GET (get-item) 端点的模式有一个额外的段,那么在编写 create-at url 时使用组前缀的想法就不够了,因为该段不会被包含在内。您最终将组合多个硬编码字符串部分。

如果上面示例中的 get-todo-item 端点有一个额外的 extra 段 - 如下例所示 - 那么 ToDo 的created-at url > ID 为 123 的项目必须是

/todos/extra/123

linkGenerator 与命名路由相结合就可以解决这个问题。

group
    .MapGet("/extra/{id}", (int id) =>
    {                
        // ...
        return new Todo { Id = id };
    })
    .WithName("GetToDo");

关于c# - 在 ASP.NET Core 7 WebApi 中使用 RouteGroupBuilder 时如何获取路由组前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74365933/

相关文章:

c# - 从集合中删除项目(NHibernate)

c# - 使 C# 用户友好地捕获 Mysql 错误

c# - 继承具有相同命名空间和相同类名的类

c# - StartIndex 不能小于零。 - 尝试更改字符串时出错

asp.net-core - ValidationSummary.ModelOnly 失败,但 ValidationSummary.All 有效

c# - ASP.NET Core Identity session 过期早于配置发生的时间

c# - 如何监视应用程序域中影子复制程序集的原始版本何时更改

c# - 在不创建新的 Edmx 文件的情况下在 EF 4 上映射外键

.net - log4net LogicalThreadContext不起作用

c# - centos 8 中 docker build net core 5.0 报错 NET SDK is not installed