ASP.NET Core Controller Basics

In this tutorial, We will introduce to you to the basic concepts of ASP.NET Core Controllers. You will learn what is a Controller and what are its responsibilities.  You will learn how to Add Controllers.  You will learn what are Controller Action Methods and the return type from these Controller Action method (i.e. Action Results).

What is a Controller

The Controller is the first component to receive the request from the User.  When a user enters a URL into the browser, The ASP.NET Core MVC routing engine maps the request to a specific controller.

For Example, the following request coming from the User

http://localhost/Customer/List

In the above case, the Controller named CustomerController is invoked.  It then invokes the List Action method and generates the response and sends it back to the User.

The Controller Responsibilities

The Controller has three major responsibilities

  • Handle the Request
  • Build a Model
  • Send the Response

Handle the Request

The Controller is responsible to Handle Request from the User.

Builds the Module

The Controller Action method executes the application logic and builds a model

Sends the Result

Finally, it should return the Result in HTML/File/Json/XML or whatever the format requested by the user.

Adding a Controller

Controllers are nothing but regular .NET Classes. By Convention, Controllers Reside in the project’s root-level Controllers folder.

You can create a Controller by selecting the Controllers folder and right-click and select the Controller Option as shown below.

Add New Controller Via Scaffolding
Next,  you are presented with the various scaffolding option. There are two main options here.

  • MVC Controller
  • API Controller

Add Scaffold for MVC Controllers

Both the MVC and API Controller inherits from the same Controller class and there is not much difference between them, except that API Controller is expected to return the data in serialized to format to the client.

Further, we have three options under both types of controllers.

  • Empty
  • With Read/Write Actions
  • With Views, using entity framework

There is another way to create a Controller. Right Click on Controllers folder and select Add new item and select the MVC Controller in the Template. This will create an Empty Controller.

The Controllers in ASP.NET Core Inherit from Controller class which in turn inherits from the ControllerBaseClass. These two base classes provide several useful helper methods.

The controller class must satisfy at least one of the following conditions

  • The class name is suffixed with “Controller”.
  • The class inherits from a class whose name is suffixed with “Controller”.
  • The class is decorated with the [Controller] attribute.

Action Methods

Any Public method exposed by a Controller is called an Action method.

The Action method gets called when a user enters a particular URL in the browser.

For Example, http://localhost/Customer/List will invoke the List Action method in the CustomerController.

Action methods should call the service layer to respond to the request.  The Service layer generally should query or update the database using data access layer and then map the results into a model and pass it back to the Action method.

Action method then invokes the View with the model to generate the response.

Any public method in a controller class can be invoked by anyone located anywhere in the world. So be careful when you place a public method in the controller.

When Creating an Action method you should remember the following

  • Action methods Must be a public method
  • The Action method cannot be a Static method or an Extension method.
  • The Constructor, getter or setter cannot be used.
  • Inherited methods cannot be used as the Action method.
  • Action methods Cannot contain ref or out parameters.
  • Action Methods cannot contain the attribute [NonAction].
  • Action methods cannot be overloaded

Routing

The Routing Module is an Important part of the ASP.NET Core.  This Module inspects the incoming URLs and invokes the right Controller Actions associated with that request.

For Example, the incoming URL http://localhost/Customer/List first goes through the Routing Module. The Routing Module inspects this URL and chooses the appropriate Controller to handle the request. It then instantiates the Controller and invokes the correct Action method.

We will discuss the Routing in ASP.Net core Tutorial. The Routing could be either Convention based or Attribute based.  The Routes are defined using the convention or as an attribute of the Action method.  The Routing module uses the Routes map the request to the Controller Action. The Routes can be given ActionName attributes to alias the Action Method names. The HTTP Action Verbs can be used to control the Action method based on HTTP request method. Further, we can use Route Constraints to distinguish between Similar looking routes.

Return Types

The Action methods are responsible for handling use request and generating the response that is ultimately displayed to the end user. The Response could be HTML page, Json, XML or a file to download.

A Controller action can return anything it wants. For example, the following Action method returns a string.

Generally, a controller action should return something called an Action Result. The Each return type like HTML, Json or string etc have their own Action Result, which inherits from the ActionResult base class. The ActionResult base class is an abstract class.

For Example to generate HTML response we use ViewResult. To generate string or text result, we use ContentResult. Both ViewResult and ContentResult inherit from the ActionResult.

ASP.NET Core MVC framework has built-in support for several types of Action results including

  • ViewResult – Represents HTML and markup.
  • EmptyResult – Represents no result.
  • RedirectResult – Represents a redirection to a new URL.
  • JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  • JavaScriptResult – Represents a JavaScript script.
  • ContentResult – Represents a text result.
  • FileContentResult – Represents a downloadable file (with the binary content).
  • FilePathResult – Represents a downloadable file (with a path).
  • FileStreamResult – Represents a downloadable file (with a file stream).

Summary

In this tutorial, we introduced you to the some of the basic concepts of ASP.NET Core  MVC controllers, controller actions, and controller action results. In the next few article, we will inspect each of those in detail

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top