C# nameof(NameofController)的RedirectToAction无法找到该操作
根据内联文档,C# nameof(NameofController)的RedirectToAction无法找到该操作,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,根据内联文档,ControllerBase.RedirectToAction采用操作名称和控制器名称: // Parameters: // actionName: // The name of the action. // // controllerName: // The name of the controller. public virtual RedirectToActionResult RedirectToAction(string actionName, st
ControllerBase.RedirectToAction
采用操作名称和控制器名称:
// Parameters:
// actionName:
// The name of the action.
//
// controllerName:
// The name of the controller.
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName);
现在,假设我想重定向到以下操作:
[Route("Whatever")]
public class WhateverController : Controller
{
[HttpGet("Overview")]
public IActionResult Overview()
{
return View();
}
}
当然,我想使用nameof
操作符:
[Route("Home")]
public class HomeController : Controller
{
[HttpGet("Something")]
public IActionResult Something()
{
return RedirectToAction(
nameof(WhateverController.Overview), // action name
nameof(WhateverController) // controller name
);
}
}
但该调用失败,出现错误invalidoOperationException:没有路由与提供的值匹配。
我知道我可以将控制器名称硬编码为“WhateverController”,而不是使用
nameof
操作符,但是有没有办法从类名中获取正确的名称?问题是nameof(WhateverController)
返回WhateverController
,而不是您和路由系统期望的(无论什么)。您可以使用
nameof(WhateverController)。替换(“Controller”,”)
来获取所需的内容
编辑:如果您所需要的不是硬编码的控制器/操作名称,那么最好使用这样的名称。
nameof(WhateverController)
将返回“WhateverController”RedirectToAction
希望以“任意”的形式使用控制器的名称。使用
nameof
而不是硬编码字符串绝对是好的(在很多情况下),但在这种情况下,这似乎是让您感到不舒服的地方。我不喜欢扩展方法,因为在这种情况下它会污染API,但如果您愿意,这并不是最坏的主意
public static class StringExtensions
{
/// <summary>
/// Removes the word "Controller" from the string.
/// </summary>
public static string RemoveController(this string value)
{
string result = value.Replace("Controller", "");
return result;
}
}
更好的方法 创建一个基本控制器并将该方法放入其中,而不是扩展方法
public class ControllerBase : Controller
{
/// <summary>
/// Removes the word "Controller" from the string.
/// </summary>
protected string _(string value)
{
string result = value.Replace("Controller", "");
return result;
}
}
您可以从上面的用法中看到
\uu
是如何避开障碍并提高可读性的。同样,如果您不喜欢,我会这样做,您不需要这样做。您可以使用package@MohammadDaliri你能补充一下吗?这正是我想要的。等等,就这些?我希望MVC框架能够提供一种方法来实现这一点,而不必手动完成。@Métoule,它不会,但您可以通过使用它来获得您想要的。
public class ControllerBase : Controller
{
/// <summary>
/// Removes the word "Controller" from the string.
/// </summary>
protected string _(string value)
{
string result = value.Replace("Controller", "");
return result;
}
}
public class SomeController : ControllerBase
{
public ActionResult Index(string value)
{
return RedirectToAction(nameof(WhateverController.Overview), _(nameof(WhateverController)));
}
}