1

I'm new to ASP.NET MVC and I'm confused about how in a compiled language like C#, class names can have any meaning after the project has been built. Can someone explain to me how the building process takes

public class SomePageController : Controller {
     public ActionResult Index() { return View(); }
}

and grabs the names SomePage and Index to create a URL map SomePage/Index that calls the function Index()? I only understand how this works if there is some other C# file that somehow able to look at all classes derived from the Controller class and get a string that is their name without the suffix "Controller". But that seems weird to me coming from a C++ background because I've never seen a way that a language can have of variables referencing their own name, nor have I ever seen a way to iterate through all classes derived from a certain class.

Maybe someone can show me how to write a C# procedure like

public class SomePageController : Controller {
     public ActionResult Index() { return View(); }
}

public class SomeOtherPageController : Controller {
     public ActionResult Index() { return View(); }
}

public void printPageNames ( void )
{
    // ... Will print "SomePage, SomeOtherPage" to the console
}
ekad
  • 14,436
  • 26
  • 44
  • 46
  • 1
    Mapping to pages has little do with URL's. URL's map to an action method on a controller, either via convention based routing or attribute routing. The view is then selected by action method. To see where the framework looks to find the view, just remove the view and hit the Action Method. The system will conveniently show you a list of places that it looks for the view. – mason May 07 '15 at 12:28
  • TBH it more the convention than any programming magic trick - just like @mason said. When you have URL like /client/view and convention is not overridden, application looks for view file in Views/Client/View.cshtml(because it should corresponds to Views/Controller/Action.cshtml). – kamil-mrzyglod May 07 '15 at 13:38

1 Answers1

2

What you need to read into is Reflection. It allows you to look at all of the classes, properties, etc within an assembly.

To directly answer your question, Jon Skeet has the starting point of how to accomplish this.

Your code would look something like this:

var assembly = Assembly.GetExecutingAssembly();

foreach (var controller in assembly.GetTypes().Where(a => a.Name.EndsWith("Controller"))
{
    Console.WriteLine(controller.Name.TrimEnd("Controller"));
}
Community
  • 1
  • 1
krillgar
  • 12,596
  • 6
  • 50
  • 86