在 ASP.NET Core 2.2 控制器上,我尝试以 3 种方式生成链接:
var a = Url.Action(action: "GetContentByFileId", values: new { fileId = 1 });
var b = _linkGenerator.GetUriByAction(HttpContext, action: "GetContentByFileId", controller: "FileController", values: new { fileId = 1 });
var c = _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext, action: "GetContentByFileId", controller: "FileController", values: new { fileId = 1 });
结果
在“a”中,使用 Url.Action 我得到了正确的链接......
在“b”和“c”中,我得到空值,我提供相同的数据......我想。
我在控制器中注入 LinkGenerator 并且它不为空...
我也在注入 HttpContextAccessor 并且在启动时有:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
文件控制器是:
[ApiVersion("1.0", Deprecated = false), Route("v{apiVersion}")]
public class FileController : Controller {
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly LinkGenerator _linkGenerator;
public FileController(IHttpContextAccessor httpContextAccessor, LinkGenerator linkGenerator) {
_httpContextAccessor = httpContextAccessor;
_linkGenerator = linkGenerator;
}
[HttpGet("files/{fileId:int:min(1)}")]
public async Task<IActionResult> GetContentByFileId(FileGetModel.Request request) {
// Remaining code
}
我错过了什么?
更新
正如 TanvirArjel 回答的那样,除了控制器后缀之外,我还能够查明问题。
如果我注释以下代码行,所有 url 都是正确的:
[ApiVersion("1.0", Deprecated = false), Route("v{apiVersion}")]
但是,如果我在启动时添加前面的代码行和以下代码:
services.AddApiVersioning(x => {
x.ApiVersionSelector = new CurrentImplementationApiVersionSelector(x);
x.AssumeDefaultVersionWhenUnspecified = true;
x.DefaultApiVersion = new ApiVersion(1, 0);
x.ReportApiVersions = false;
});
然后网址变为空...
此 ApiVersion 在文件之前添加的是“v1.0”,因此它变为“v1.0/files”。
所以linkGenerator应该变成:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});
问题
有没有办法在不指定的情况下将 apiVersion 集成到 LinkGenerator 中?