ASP.NET Core 2 Fundamentals
上QQ阅读APP看书,第一时间看更新

Role of the Controller in ASP.NET MVC Applications

A controller does the job of receiving the request and producing the output based on the input data in ASP.NET MVC. You can imagine controllers as the entrance point to your business flow that organizes the application flow.

If you are intending to write a complex application, it is best to avoid business logic in your controllers. Instead, your controllers should call your business logic. In this way, you can keep the core part of your business technology-agnostic.

At the high level, the controller orchestrates between the model and the view, and sends the output back to the user. This is also the place where authentication is usually done through action filters. Action filters are basically interceptors and will be discussed in detail in the Filters section of this chapter. The following diagram illustrates the high-level flow of a request (with the steps) in ASP.NET MVC and shows us how the controller fits into the big picture:

The following is the sequence of events that will happen at the high level when the user is accessing the ASP.NET Core application:

  1. The user types the URL in the browser.
  2. Based on the pattern of the URL, the routing engine selects the appropriate controller.
  3. The controller talks to the model to get any relevant data through its action methods. Action methods are methods within a controller class.
  4. The controller then passes the data to the view to present it in a viewable format, typically as HTML elements.
  5. The view is finally delivered to the user, which he would be viewing in his browser.

Before discussing the controller, let us discuss the fundamentals of routing concepts, as the routing engine only chooses the appropriate controller and action method at runtime.