C#中的MVC控制器是否有nameof()运算符?

Bla*_*ise 21 c# asp.net-mvc

新引入的nameof运算符可以使我的代码成为"打字".

代替

return RedirectToAction("Edit");
Run Code Online (Sandbox Code Playgroud)

我们可以写

return RedirectToAction(nameof(Edit));
Run Code Online (Sandbox Code Playgroud)

但是要获得控制器的名称并不是那么简单,因为我们有一个Controller后缀.只是想知道我是否想要一个

return RedirectToAction(nameof(Index), controllernameof(Home));
Run Code Online (Sandbox Code Playgroud)

代替

return RedirectToAction("Index", "Home");
Run Code Online (Sandbox Code Playgroud)

我们如何实现controllernameof运营商?

Jon*_*yan 8

完全理解您不想使用魔法弦的愿望!在上面的评论和这篇文章之间。我已经开始在我的其他控制器继承的基本控制器中使用以下内容:

public RedirectToRouteResult RedirectToAction<TController>(Expression<Func<TController, string>> expression, object routeValues)
{
    if (!(expression.Body is ConstantExpression constant))
    {
        throw new ArgumentException("Expression must be a constant expression.");
    }

    string controllerName = typeof(TController).Name;

    controllerName = controllerName.Substring(0, controllerName.LastIndexOf("Controller"));

    return RedirectToAction(constant.Value.ToString(), controllerName, routeValues);
}

public RedirectToRouteResult RedirectToAction<TController>(Expression<Func<TController, string>> expression)
{
    return RedirectToAction(expression, null);
}
Run Code Online (Sandbox Code Playgroud)

然后我使用:

 return RedirectToAction<HomeController>(a => nameof(a.Index));
Run Code Online (Sandbox Code Playgroud)

 return RedirectToAction<HomeController>(a => nameof(a.Index), new { text= "searchtext" });
Run Code Online (Sandbox Code Playgroud)


ste*_*kil 6

也许像下面这样的扩展方法会满足您的需求:

public static class ControllerExtensions
{
  public static string ControllerName(this Type controllerType)
  {
     Type baseType = typeof(Controller);
     if (baseType.IsAssignableFrom(controllerType))
     {
        int lastControllerIndex = controllerType.Name.LastIndexOf("Controller");
        if (lastControllerIndex > 0)
        {
           return controllerType.Name.Substring(0, lastControllerIndex);
        }
     }

     return controllerType.Name;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样调用:

return RedirectToAction(nameof(Index), typeof(HomeController).ControllerName());
Run Code Online (Sandbox Code Playgroud)


小智 5

不,没有这种可能性。您可能会被测试T4MVC代替使用。

T4MVC-用于ASP.NET MVC应用程序的T4模板,该模板创建强类型的帮助程序,从而消除了许多地方使用文字字符串的情况。

例如代替

@Html.ActionLink("Dinner Details", "Details", "Dinners", new { id = Model.DinnerID }, null)
Run Code Online (Sandbox Code Playgroud)

T4MVC 让你写

@Html.ActionLink("Dinner Details", MVC.Dinners.Details(Model.DinnerID))
Run Code Online (Sandbox Code Playgroud)


小智 5

解决 XControllerController 问题的解决方案看起来更像是:

String nameStr = nameof(FlightControllerController);
nameStr = nameStr.Substring(0, nameStr.LastIndexOf("Controller"));
Run Code Online (Sandbox Code Playgroud)


小智 5

在 C# 8 及更高版本中,您可以使用范围运算符删除最后 10 个字符:

\n
nameof(AccountController)[..^10]\n
Run Code Online (Sandbox Code Playgroud)\n

如果您不喜欢简洁的话,则可以将 10 替换为常量。

\n