user3800527 user3800527 - 1 year ago 68
C# Question

How does MVC know which controller to call, when they are not annotated?

first time i respond on stackexchange like Email form

my question is not about aspx pages, its about core MVC6 core can do without aspx pages, it uses Razor pages.
Another reason for not removing this question is for helping other students like me who endup with the same question i had based on this course, as i later found the proper words, there are various websites where people seam confused about this, and while i adept to this new concept. I hope you can keep the question more people following the Microsoft online course can stumble into this, as on the video its not realy clear. (lots of things are discussed and this is quite a big one between all the other explanations in that movie).

At some point in this course video, they have defined a Controller that responds to an URL. MVC somehow understands when you request

, that it should call the
which then returns "hey it's scott".

The controllers look like this:

namespace WebApplication1.Controller
public class MariaController
public string Index() => "Hello from index mvc";
public string Maria() => "Hello from Maria mvc";

public class ScottController
public string index()
return "hey it's scott";

Notice in the code above there is no
annotation, yet somehow this code knows about that the class
should respond to the
URL, despite it doesn't have a "name property" or so with the value "Scott" to check against.

Is it that with Controller classes, the name "ScottController" is split up and Controller is removed, so MVc knows this a class that handles requests to the

Answer Source

It's entirely the other way around, and all has to do with routing. The site-relative URI /Scott defaults to these route values:

  • Controller: Scott
  • Action: Index

This is because of conventions. The default convention is /{controller}/{action}, where the action is optional and defaults to Index.

So when you request /Scott, MVC's routing will go and look for a controller named ScottController, all because of conventions. See also Why do MVC controllers have to have the trailing 'Controller' convention on their class name?

Then, because of the action being absent from the request-URI, it will try and find the default action named Index, which returns "hey it's scott".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download