In ASP.NET Core, a controller is a class that handles incoming HTTP requests, processes them, and returns responses to the client. Controllers are a fundamental part of the Model-View-Controller (MVC) architectural pattern, which separates the application into three main components: models, views, and controllers. This separation of concerns helps in organizing code, making it more maintainable and testable.

Key Responsibilities of a Controller

  • Handling Requests: Controllers receive HTTP requests from clients and determine how to respond based on the request data.
  • Processing Data: Controllers can interact with models to retrieve, update, or delete data as needed. They often serve as intermediaries between the view and the model.
  • Returning Responses: After processing a request, controllers return responses, which can be in various formats such as HTML, JSON, or XML.
  • Routing: Controllers are associated with specific routes, allowing the ASP.NET Core routing system to direct requests to the appropriate controller actions.

Creating a Controller in ASP.NET Core

To create a controller in an ASP.NET Core application, follow these steps:

Step 1: Create a New Controller Class

Controllers are typically placed in the Controllers folder of an ASP.NET Core project. Below is an example of a simple controller named HomeController.

        
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
// Action method for the Index view
public IActionResult Index()
{
return View(); // Returns the Index view
}

// Action method for the About view
public IActionResult About()
{
return View(); // Returns the About view
}
}

Explanation of the Sample Code

In the sample code above:

  • Controller Class: The HomeController class inherits from the Controller base class, which provides various methods and properties for handling requests and returning responses.
  • Action Methods: The Index and About methods are action methods that handle requests to their respective routes. Each method returns an IActionResult, which represents the result of the action.
  • Returning Views: The View() method is called to return a view associated with the action. By default, it looks for a view with the same name as the action method in the Views/Home folder.

Routing to Controllers

ASP.NET Core uses routing to direct incoming requests to the appropriate controller and action method. By default, the routing configuration is set up in the Startup class. Below is an example of how routing is configured:

        
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(); // Adds MVC services
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); // Default route
});
}
}

Explanation of Routing Configuration

In the routing configuration:

  • Default Route: The default route pattern {controller=Home}/{action=Index}/{id?} specifies that if no specific controller or action is provided in the URL, the application will route the request to the HomeController and invoke the Index action method. The {id?} part indicates that the id parameter is optional.

Conclusion

Controllers in ASP.NET Core are essential components that manage the flow of data between the model and the view. They handle incoming requests, process data, and return appropriate responses, making them a crucial part of the MVC architecture. By organizing application logic within controllers, developers can create maintainable and scalable web applications that adhere to best practices.