无法让 LinkGenerator 创建 API 操作的路径 [英] Cannot get LinkGenerator to create a path to API action

查看:39
本文介绍了无法让 LinkGenerator 创建 API 操作的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务内部 - 控制器外部创建指向 API 端点的链接.

I am trying to create a link to an API endpoint from inside a Service - outside of a Controller.

这是控制器及其基类.我在 ASP.NET Core 中使用 API 版本控制和区域.

Here is the Controller and its base class. I am using API versioning and Areas in ASP.NET Core.

[ApiController]
[Area("api")]
[Route("[area]/[controller]")]
public abstract class APIControllerBase : ControllerBase
{

}

[ApiVersion("1.0")]
public class WidgetsController : APIControllerBase
{
    [HttpGet("{id}"]
    [Produces("application/json")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<Widget>> Get(Guid id)
    {
        // Action...
    }
}

API 版本控制配置:

API Versioning configuration:

services.AddApiVersioning(options =>
{
    options.ApiVersionReader = ApiVersionReader.Combine(
        new QueryStringApiVersionReader
        {
            ParameterNames = { "api-version", "apiVersion" }
        },
        new HeaderApiVersionReader
        {
            HeaderNames = { "api-version", "apiVersion" }
        });
});

以及我实际尝试使用 LinkGenerator 的地方:

And where I actually try to use LinkGenerator:

_linkGenerator.GetPathByAction(
    _accessor.HttpContext,
    action: "Get",
    controller: "Widgets",
    values: new
    {
        id = widget.Id,
        apiVersion = "1.0"
    }
)

我已经尝试了 LinkGenerator 的各种变体.我使用了 HttpContext 重载,我使用了没有它的重载,我已经包含了 apiVersion 参数并省略了它,我已经从控制器中完全删除了 [ApiVersion] .一切总是返回null.如果我路由到像 GetPathByAction("Index", "Home") 这样的普通 MVC 控制器,我会得到一个像我应该的 URL,所以我认为它必须与我的 API 区域有关,或者版本控制设置.

I've tried all manner of variations for the LinkGenerator. I've used the HttpContext overload, I've used the overload without it, I've included the apiVersion parameter and omitted it, I've removed [ApiVersion] from the Controller entirely. Everything always comes back null. If I route to a normal MVC Controller like GetPathByAction("Index", "Home") I get a URL like I should though, so I'm think it must be related to my API Areas, or versioning setup.

推荐答案

您没有指定区域:

_linkGenerator.GetPathByAction(
    _accessor.HttpContext,
    action: "Get",
    controller: "Widgets",
    values: new
    {
        area = "api",
        id = widget.Id,
        apiVersion = "1.0"
    }
)

这篇关于无法让 LinkGenerator 创建 API 操作的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆