.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
orGetUriByRouteValues
with arouteName
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/