Use [Controller] and [NonController] Attributes in ASP.NET Core
ASP.NET Core MVC uses certain conventions when it comes to naming the
controllers. Although these defaults work as expected in many cases, at times
you may want to take charge of the controller naming. Luckily, ASP.NET Core
provides two attributes - [Controller] and [NonController] - that can be used to
alter this default behavior. To that end this article shows how to use these
attributes with simple examples.
Default convention for controller naming
Consider a simple controller of "Hello World" application :
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Hello World!";
return View();
}
}
Here, the controller class name ends with "controller" and is inherited from
Microsoft.AspNetCore.Mvc.Controller base class.
If you run this simple application you will get this obvious output in the
browser:

Controller inheritance
Now, change the controller name as shown below :
public class Home : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Hello World!";
return View();
}
}
This time we removed the "controller" suffix from the controller name but
Home still inherits from Controller base class.
A sample run of the modified application will produce output as before
because of this inheritance.
Using [Controller] attribute
Now change the controller as shown below :
public class Home
{
public string Index()
{
return "Hello World!";
}
}
In this case, the Home class neither has "controller" suffix nor it inherits
from the Controller base class.
If you try to run the application it won't work as expected because ASP.NET
Core can no longer identify Home class as a controller.
To fix the problem, mark the Home class with [Controller] attribute as shown
below:
[Controller]
public class Home
{
public string Index()
{
return "Hello World!";
}
}
Decorating the Home class with [Controller] attribute identifies it as a MVC
controller and the application works as expected.
Using [NonController] attribute
Not all the classes with "controller" suffix are controllers. For example,
you might be developing a traffic monitoring system that has a business domain
specific class named TrafficController. Now, this class is not an MVC controller
but ASP.NET Core will treat it as a controller class due to its "controller"
suffix.
How to fix this issue? Just decorate the TrafficController class with [NonController]
attribute..
[NonController]
public class TrafficController
{
public string Index()
{
return "Hello World!";
}
}
That's it for now! Keep coding!!