Is there a nameof() operator for MVC controllers in C#?

Maybe an extension method like the following would suit your needs:

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;
  }
}

Which you could invoke like so:

return RedirectToAction(nameof(Index), typeof(HomeController).ControllerName());

Leave a Comment