在ASP.NET Core 3.x MVC中将nameof()与Url.Action()和异步方法一起使用 [英] Using nameof() with Url.Action() and async methods in ASP.NET Core 3.x MVC
问题描述
假设我有一个ASP.NET Core 3.0 MVC应用程序,该应用程序具有一个包含两个动作并使用基于属性的路由的简单控制器:
Let's say I have a ASP.NET Core 3.0 MVC application, which features a simple controller containing two actions and using attribute based routing:
[Route("home")]
public class HomeController : Controller
{
public static string ControllerName { get; } = "Home";
public HomeController()
{
}
string GenerateUrls()
{
string url1 = Url.Action(nameof(Action1), ControllerName);
string url2 = Url.Action(nameof(Action2Async), ControllerName);
return $"Action1: '{url1}'\nAction2: '{url2}'";
}
[HttpGet("a1")]
public IActionResult Action1()
{
return Ok(GenerateUrls());
}
[HttpGet("a2")]
public async Task<IActionResult> Action2Async()
{
await Task.CompletedTask;
return Ok(GenerateUrls());
}
}
因此,调用任何一个操作都应该会产生一个显示两个操作的URL的页面.
So calling either action should just yield a page showing URLs for both actions.
打开/home/a1
和/home/a2
会正确调用相应的操作,但是输出有点意外:
Opening /home/a1
and /home/a2
correctly calls the respective actions, but the output is kind of unexpected:
Action1: '/home/a1'
Action2: ''
这表明Url.Action()
为第二个操作返回了一个空字符串,而对于第一个操作则完全正常.
This indicates that Url.Action()
returned an empty string for the second action, while it worked perfectly fine for the first action.
在调试了一段时间之后,我发现了博客文章将此问题归结为ASP.NET Core 3.0中的重大更改,其中Async
后缀被Url.Action()
忽略了.
After debugging this for quite a while, I found a blog post tracking down this very problem to a breaking change in ASP.NET Core 3.0, where the Async
suffix is somehow ignored by Url.Action()
.
作者通过将字符串硬编码为动作名称(在我的情况下为"Action1"
和"Action2"
)解决了此问题.他还上传了一些示例代码来再现这种行为.
The author fixed this problem by hard-coding strings as action names ("Action1"
und "Action2"
in my case). He also uploaded some example code reproducing this behavior.
但是,我真的更喜欢保留nameof
,以避免以后出现重命名/重构问题.
However, I would really prefer to keep the nameof
, to avoid later problems with renaming/refactoring.
是否有一种干净的方法来使用nameof
或其他类型安全的结构为Url.Action
函数提供后缀为Async
的方法?
Is there a clean way to use nameof
or other type-safe constructs to supply a method with Async
suffix to the Url.Action
function?
推荐答案
所描述的行为是由ASP.NET Core 3.0引入的重大更改引起的.
The described behavior is caused by a breaking change introduced with ASP.NET Core 3.0.