我试图从服务内部创建一个到API端点的链接 - 在Controller之外。
这是Controller及其基类。我正在使用API版本和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版本配置:
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参数并省略了它,我已经完全从Controller中删除了[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"
}
)