在ASP.NET Core 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 });
结果
在"a"中,使用Url。操作我得到了正确的链接。。。
在"b"one_answers"c"中,我得到了null,并且我提供了相同的数据。。。我想。
我正在控制器中注入LinkGenerator,它不是null。。。
我也在注入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回答的Controller后缀之外,我还能够指出问题。
如果我评论以下代码行,所有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;
});
然后URL变为空。。。
这个ApiVersion在文件之前添加了"v1.0",因此它变成了"v1.0/files"。
因此链接生成器应该变成:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});
问题
有没有一种方法可以在不指定的情况下在LinkGenerator中集成apiVersion?
问题是您使用的控制器名称后缀为Controller
。请从控制器名称中删除Controller
后缀,并按如下方式写入:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { FileId = 1 }
);
现在它应该起作用了。
app.UseEndpoints(endpoints =>
{
// Default route
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Account}/{action=Login}/{id?}");
});
services.AddMvc(options => options.EnableEndpointRouting = true);
string url = _generator.GetUriByAction("index", "home", null,
_accessor.HttpContext.Request.Scheme, _accessor.HttpContext.Request.Host);
var url1 = _generator.GetPathByAction("index", "home",
new { FileId = 1 });