Mig*_*ura 6 c# asp.net-core asp.net-core-2.2
在 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 });
Run Code Online (Sandbox Code Playgroud)
结果
在“a”中,使用 Url.Action 我得到了正确的链接......
在“b”和“c”中,我得到 null 并且我提供相同的数据......我认为。
我正在控制器中注入 LinkGenerator,它不为空......
我还注入了 HttpContextAccessor 并且在启动时有:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
文件控制器是:
[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
}
Run Code Online (Sandbox Code Playgroud)
我缺少什么?
更新
正如 TanvirArjel 所回答的那样,我能够查明除控制器后缀之外的问题。
如果我注释以下代码行,则所有网址都是正确的:
[ApiVersion("1.0", Deprecated = false), Route("v{apiVersion}")]
Run Code Online (Sandbox Code Playgroud)
但是如果我在启动时添加前面的代码行和以下代码:
services.AddApiVersioning(x => {
x.ApiVersionSelector = new CurrentImplementationApiVersionSelector(x);
x.AssumeDefaultVersionWhenUnspecified = true;
x.DefaultApiVersion = new ApiVersion(1, 0);
x.ReportApiVersions = false;
});
Run Code Online (Sandbox Code Playgroud)
然后url就变成空了...
此 ApiVersion 在文件之前添加的是“v1.0”,因此它变为“v1.0/files”。
所以 linkGenerator 应该变成:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { apiVersion = "1.0", fileId = 1
});
Run Code Online (Sandbox Code Playgroud)
问题
有没有一种方法可以在不指定的情况下将 apiVersion 集成到 LinkGenerator 中?
问题是您使用的控制器名称带有Controller后缀。请删除Controller控制器名称中的后缀并编写如下:
var b = _linkGenerator.GetUriByAction(HttpContext,
action: "GetContentByFileId",
controller: "File",
values: new { FileId = 1 }
);
Run Code Online (Sandbox Code Playgroud)
现在应该可以了。
| 归档时间: |
|
| 查看次数: |
4376 次 |
| 最近记录: |