user3800527 user3800527 - 1 month ago 5
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 asp.net core MVC6
asp.net 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

http://localhost/Scott
, that it should call the
ScottController
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
[HttpGet("/Maria")]
or
[HttpGet("/Scott")]
annotation, yet somehow this code knows about that the class
ScottController
should respond to the
/Scott
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
/Scott
URI?

Answer

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".