名称为(NameofController)的RedirectToAction无法定位操作

Mét*_*ule 0 c# asp.net-core-mvc asp.net-core

根据内联文档,ControllerBase.RedirectToAction获取操作名称和控制器名称:

// Parameters:
//   actionName:
//     The name of the action.
//
//   controllerName:
//     The name of the controller.
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName);
Run Code Online (Sandbox Code Playgroud)

现在,让我们假设我想重定向到以下操作:

[Route("Whatever")]
public class WhateverController : Controller
{
    [HttpGet("Overview")]
    public IActionResult Overview()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,我想使用nameof运算符":

[Route("Home")]
public class HomeController : Controller
{
    [HttpGet("Something")]
    public IActionResult Something()
    {
        return RedirectToAction(
            nameof(WhateverController.Overview), // action name
            nameof(WhateverController) // controller name
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这个调用因错误而失败 InvalidOperationException: No route matches the supplied values.

我知道我可以将控制器名称硬编码为"what"而不是使用nameof运算符,但有没有办法从类名中获取正确的名称?

Ash*_*deh 5

问题是nameof(WhateverController)返回WhateverController,而不是你和路由系统所期望的(随便).
你可以nameof(WhateverController).Replace("Controller", "")用来得到你想要的东西.

编辑:
如果你想要的不是硬编码的控制器/动作名称,那么最好使用像R4MVC这样的东西.