Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do ASP.NET MVC Controller classes need to be public?

When I make a change to the access modifier of a controller class it results in an error. If I make the accessibility of an action method non-public then it also results in an error (specifically a page not found error). Why is this the case?

like image 793
Pramod Thakur Avatar asked Dec 13 '14 09:12

Pramod Thakur


People also ask

What is a public method of a controller class?

Controller class contains public methods called Action methods. Controller and its action method handles incoming browser requests, retrieves necessary model data and returns appropriate responses. In ASP.NET MVC, every controller class name must end with a word "Controller".

Why are controllers required in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

What is the purpose of controller class?

A controller class is normally a class part of the Model View Controller (MVC) pattern. A controller basically controls the flow of the data. It controls the data flow into model object and updates the view whenever data changes.

Is it necessary for the MVC controller class to inherit from the base class controller?

Standard view-based MVC controllers should inherit from Controller . In both frameworks, controllers are used to organize sets of action methods.


1 Answers

By default if you not specify any access modifier for a class then it will default to internal in C#. Only code in the same assembly can access a class that is internal. So if your controller is internal, the code that creates a controller instance upon receiving a request would have to be in your assembly.

But controller creation code is present in the System.Web.Mvc assembly and by default DefaultControllerFactory is responsible for creating controllers. If your code is present in, for example, the MvcApplication1 assembly then DefaultControllerFActory can not find your controller classes without the public access modifier so it is not able to instantiate them.

If you want to build a tightly coupled ASP.NET MVC application (which it is not it designed for) then theoretically you could do it following way.

  1. Get the MVC source code if available.
  2. Then build your code in same assembly.
like image 184
dotnetstep Avatar answered Sep 19 '22 08:09

dotnetstep