Val*_*tor 4 c# url-routing asp.net-core-mvc asp.net-core
我正在尝试从服务内部(控制器外部)创建到 API 端点的链接。
这是控制器及其基类。我在 ASP.NET Core 中使用 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...
}
}
Run Code Online (Sandbox Code Playgroud)
API 版本控制配置:
services.AddApiVersioning(options =>
{
options.ApiVersionReader = ApiVersionReader.Combine(
new QueryStringApiVersionReader
{
ParameterNames = { "api-version", "apiVersion" }
},
new HeaderApiVersionReader
{
HeaderNames = { "api-version", "apiVersion" }
});
});
Run Code Online (Sandbox Code Playgroud)
我实际上尝试使用 LinkGenerator 的地方:
_linkGenerator.GetPathByAction(
_accessor.HttpContext,
action: "Get",
controller: "Widgets",
values: new
{
id = widget.Id,
apiVersion = "1.0"
}
)
Run Code Online (Sandbox Code Playgroud)
我已经尝试了 LinkGenerator 的各种变体。我使用了 HttpContext 重载,我使用了没有它的重载,我已经包含了 apiVersion 参数并省略了它,我已经[ApiVersion]完全从控制器中删除了。一切总会回来的null。如果我路由到一个普通的 MVC 控制器,就像GetPathByAction("Index", "Home")我得到一个像我应该的那样的 URL,所以我认为它必须与我的 API 区域或版本控制设置有关。
您没有指定区域:
_linkGenerator.GetPathByAction(
_accessor.HttpContext,
action: "Get",
controller: "Widgets",
values: new
{
area = "api",
id = widget.Id,
apiVersion = "1.0"
}
)
Run Code Online (Sandbox Code Playgroud)