Home > OS >  Why the class name of a Controller in ASP.NET Core MVC don't have to be suffix with Controller?
Why the class name of a Controller in ASP.NET Core MVC don't have to be suffix with Controller?

Time:01-19

I have been writing ASP.NET MVC for more then 10 years. I always know there is a convention for the Controller class must have it's name suffix with Controller. As I know, it's a hard limit on ASP.NET MVC 5 and before.

One day I saw one of my colleague write a controller in ASP.NET Core 6 like this:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers;

public class Home : Controller
{
    private readonly ILogger<Home> _logger;

    public Home(ILogger<Home> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }
}

I shocked. I can't believe there is someone would write Controller code like this. Then I see this:

A controller is an instantiable class, usually public, in which at least one of the following conditions is true:

  • The class name is suffixed with Controller.
  • The class inherits from a class whose name is suffixed with Controller.
  • The [Controller] attribute is applied to the class.

Then I know the Controller suffix is not a MUST. It's just a recommended naming rule. Without Controller-suffix, it might come with come drawback like this. I also found this post. I always believe naming controller with -Controller suffix is a good practices. I just want to know that if anyone know why ASP.NET Core teams decided not have to be naming controllers with Controller suffix?

CodePudding user response:

why the hard limit had been removed

I think the reason may as below:

From this answer we see

By not having the controller naming convention, we'd have two types with the same name hence would always have to provide namespaces to distinguish between the two. But because we do have this convention this is not necessary and no type clashes occur.

By having Controller suffix on controller types, this is not necessary.

In ASP.NET Core the namespace of the controller class is unimportant, although the tradition is maintained by tooling that continues to place controller classes always under a folder named Controllers. In fact, you can now place your controller classes in any folders and any namespaces that you wish. As long as at least one of the following conditions is true.

Besides,controllers need no Controller type name appending because after all they're just like any other class.It is a form of optimization that reduces overhead and the memory footprint.

  • Related