在一个ASP.NET核心2.2控制器上,我尝试以三种方式生成一个链接:
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 });结果
我在控制器中注入LinkGenerator,它不是空的.
我也在注射HttpContextAccessor,并且我已经启动了:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();FileController是
[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所回答的。
如果我注释以下代码行,所有urls都是正确的:
[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;
});然后urls变为空..。
这个ApiVersion在文件之前添加的是"v1.0“,所以它变成了”v1.0/file“。
因此,linkGenerator应该成为:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});问题
有没有一种方法可以在不指定apiVersion的情况下在LinkGenerator中集成它?
发布于 2019-01-22 11:43:37
问题是您使用的是带有Controller后缀的Controller名称。请从控制器名称中删除Controller后缀,并按以下方式写:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { FileId = 1 }
);现在该起作用了。
https://stackoverflow.com/questions/54305970
复制相似问题