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 key component of the Model-View-Controller (MVC) architectural pattern, which helps in organizing code and separating concerns. This guide will walk you through the steps to create a controller in an ASP.NET Core application.
Step 1: Set Up Your ASP.NET Core Project
Before creating a controller, ensure you have an ASP.NET Core project set up. You can create a new project using the .NET CLI or Visual Studio. For example, to create a new web application using the CLI, you can run:
dotnet new mvc -n MyAspNetCoreApp
This command creates a new MVC application named MyAspNetCoreApp.
Step 2: Create a New Controller Class
Controllers are typically placed in the Controllers folder of your ASP.NET Core project. To create a new controller, follow these steps:
- Navigate to the
Controllersfolder in your project. - Add a new class file named
HomeController.cs.
Sample Code for 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 HomeController class:
- Inheritance: The
HomeControllerclass inherits from theControllerbase class, which provides various methods and properties for handling requests and returning responses. - Action Methods: The
IndexandAboutmethods are action methods that handle requests to their respective routes. Each method returns anIActionResult, 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 theViews/Homefolder.
Step 3: Configure Routing
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 theHomeControllerand invoke theIndexaction method. The{id?}part indicates that theidparameter is optional.
Step 4: Create Views for the Controller
To display content returned by the action methods, you need to create corresponding views. For the HomeController, create a folder named Home inside the Views folder, and then add two view files: Index.cshtml and About.cshtml.
Sample Code for Index.cshtml
@model IEnumerable<string>
<h1>Welcome to the Index Page</h1>
<p>This is the home page of the application.</p>
Sample Code for About.cshtml
<h1>About Us</h1>
<p>This page provides information about our application.</p>
Conclusion
Creating a controller in ASP.NET Core is a straightforward process that involves setting up a new class, defining action methods, and configuring routing. By following the steps outlined above, you can effectively manage HTTP requests and responses in your web application, adhering to the MVC pattern for better organization and maintainability.
