无法让 LinkGenerator 创建 API 操作的路径
Cannot get LinkGenerator to create a path to API action
我正在尝试从服务内部(控制器外部)创建到 API 端点的 link。
这是控制器及其基础class。我在 ASP.NET 核心中使用 API 版本控制和区域。
[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版本控制配置:
services.AddApiVersioning(options =>
{
options.ApiVersionReader = ApiVersionReader.Combine(
new QueryStringApiVersionReader
{
ParameterNames = { "api-version", "apiVersion" }
},
new HeaderApiVersionReader
{
HeaderNames = { "api-version", "apiVersion" }
});
});
以及我实际尝试使用 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 区域或版本控制设置有关。
您没有指定区域:
_linkGenerator.GetPathByAction(
_accessor.HttpContext,
action: "Get",
controller: "Widgets",
values: new
{
area = "api",
id = widget.Id,
apiVersion = "1.0"
}
)
如果它对其他人有帮助,我遇到了一个与此非常相似的问题,但是该操作被命名为 GetAsync
结果表明您不能通过它的全名“GetAsync”来引用该操作,您必须在没有后缀的情况下使用它,所以只需“获取”。
我正在尝试从服务内部(控制器外部)创建到 API 端点的 link。
这是控制器及其基础class。我在 ASP.NET 核心中使用 API 版本控制和区域。
[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版本控制配置:
services.AddApiVersioning(options =>
{
options.ApiVersionReader = ApiVersionReader.Combine(
new QueryStringApiVersionReader
{
ParameterNames = { "api-version", "apiVersion" }
},
new HeaderApiVersionReader
{
HeaderNames = { "api-version", "apiVersion" }
});
});
以及我实际尝试使用 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 区域或版本控制设置有关。
您没有指定区域:
_linkGenerator.GetPathByAction(
_accessor.HttpContext,
action: "Get",
controller: "Widgets",
values: new
{
area = "api",
id = widget.Id,
apiVersion = "1.0"
}
)
如果它对其他人有帮助,我遇到了一个与此非常相似的问题,但是该操作被命名为 GetAsync
结果表明您不能通过它的全名“GetAsync”来引用该操作,您必须在没有后缀的情况下使用它,所以只需“获取”。