在ASP.NET Core 2.2控制器上,我尝试通过3种方式生成链接:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
结果
在“ a”中,使用Url.Action,我获得了正确的链接...
在“ b”和“ c”中,我得到的是空值,并且正在提供相同的数据……我认为。
我正在将LinkGenerator注入Controller中,并且它不为null ...
我也正在注入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
}
FileController是:
[ApiVersion("1.0", Deprecated = false), Route("v{apiVersion}")]
我想念什么?
更新
除了TanvirArjel回答的控制器后缀之外,我还能指出问题所在。
如果我注释以下代码行,则所有URL均正确:
services.AddApiVersioning(x => {
x.ApiVersionSelector = new CurrentImplementationApiVersionSelector(x);
x.AssumeDefaultVersionWhenUnspecified = true;
x.DefaultApiVersion = new ApiVersion(1, 0);
x.ReportApiVersions = false;
});
但是,如果我在启动时添加了上一行代码和以下内容:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});
然后网址变为空...
此ApiVersion添加的文件之前是“ v1.0”,因此它变成“ v1.0 / files”。
所以linkGenerator应该变成:
{{1}}
问题
有没有一种方法可以将apiVersion集成到LinkGenerator中而不指定它?
答案 0 :(得分:2)
问题是您使用的控制器名称后缀为Controller
。请从控制器名称中删除Controller
后缀,并编写如下:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { FileId = 1 }
);
现在应该可以了。
答案 1 :(得分:0)
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 });