On an ASP.NET Core 2.2 Controller I tried to generate a Link in 3 ways:
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 });
Result
In "a", using Url.Action I get the right link ...
In "b" and "c" I get null and I am providing the same data ... I think.
I am injecting LinkGenerator in the Controller and it is not null ...
I am also injecting HttpContextAccessor and I have on Startup:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
FileController is:
[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
}
What am I missing?
Update
I was able to pin point the problem besides Controller suffix as answered by TanvirArjel.
All urls are correct if I comment the following code line:
[ApiVersion("1.0", Deprecated = false), Route("v{apiVersion}")]
But if I add the previous code line and the following on Startup:
services.AddApiVersioning(x => {
x.ApiVersionSelector = new CurrentImplementationApiVersionSelector(x);
x.AssumeDefaultVersionWhenUnspecified = true;
x.DefaultApiVersion = new ApiVersion(1, 0);
x.ReportApiVersions = false;
});
Then the urls become null ...
What this ApiVersion is adding is "v1.0" before files so it becomes "v1.0/files".
So the linkGenerator should become:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});
Question
Is there a way to integrate apiVersion in LinkGenerator without specifying it?