新引入的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运营商?
完全理解您不想使用魔法弦的愿望!在上面的评论和这篇文章之间。我已经开始在我的其他控制器继承的基本控制器中使用以下内容:
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)
也许像下面这样的扩展方法会满足您的需求:
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模板,该模板创建强类型的帮助程序,从而消除了许多地方使用文字字符串的情况。例如代替
Run Code Online (Sandbox Code Playgroud)@Html.ActionLink("Dinner Details", "Details", "Dinners", new { id = Model.DinnerID }, null)
T4MVC让你写Run Code Online (Sandbox Code Playgroud)@Html.ActionLink("Dinner Details", MVC.Dinners.Details(Model.DinnerID))
小智 5
解决 XControllerController 问题的解决方案看起来更像是:
String nameStr = nameof(FlightControllerController);
nameStr = nameStr.Substring(0, nameStr.LastIndexOf("Controller"));
Run Code Online (Sandbox Code Playgroud)
小智 5
在 C# 8 及更高版本中,您可以使用范围运算符删除最后 10 个字符:
\nnameof(AccountController)[..^10]\nRun Code Online (Sandbox Code Playgroud)\n如果您不喜欢简洁的话,则可以将 10 替换为常量。
\n