Microsoft Orange Badge Microsoft Orange Badge - 3 months ago 11
ASP.NET (C#) Question

How does ASP.NET MVC associate page names with class names?

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
}

Answer

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