ASP.NET CORE MVC - Create Your First MVC Application

ASP.NET CORE MVC TUTORIAL SERIES · PART 1

Create Your First ASP.NET Core MVC Application

Create the Product Management System with the .NET CLI, explore the generated MVC project, understand the role of Program.cs, run the development server, and trace the first request from the browser to an MVC controller and view.

Objective

By the end of this tutorial, you will have a working ASP.NET Core MVC application targeting .NET 8 and will understand the purpose of the main files and folders generated by the MVC template.

Lab environment used in this series

This tutorial assumes a Xubuntu virtual machine with Linux username xubuntu. Example home-directory paths therefore use /home/xubuntu.

In this tutorial
  1. Review the starting environment
  2. Create the MVC project
  3. Open the project in Visual Studio Code
  4. Explore the project structure
  5. Understand the project file
  6. Understand Program.cs
  7. Understand routing
  8. Examine the default controller and views
  9. Run the application
  10. Understand the development server
  11. Make a small change
  12. Stop and restart the application
  13. Complete a hands-on exercise

1. Starting Point

Part 0 prepared the development environment. Before creating the application, confirm that the .NET 8 SDK is available.

dotnet --version

If you have several SDK versions installed, you can also run:

dotnet --list-sdks

This series targets .NET 8. We will therefore explicitly specify net8.0 when creating the project.

Why specify the framework?

A computer may contain a newer .NET SDK. Explicitly specifying --framework net8.0 keeps this tutorial series consistent even when other SDK versions are installed.

2. Create the Course Working Directory

Open the Xubuntu Terminal and begin from your home directory:

cd ~

Create a working directory for this ASP.NET Core MVC tutorial series:

mkdir aspnet-mvc-tutorial

Enter the new directory:

cd aspnet-mvc-tutorial

Confirm the current directory:

pwd

For the xubuntu user, the output should be:

/home/xubuntu/aspnet-mvc-tutorial
Why create a separate working directory?

The aspnet-mvc-tutorial directory keeps the projects for this tutorial series together and separate from unrelated files in your home directory.

3. Create the MVC Application

The .NET SDK contains project templates. The ASP.NET Core MVC template uses the short name mvc.

Create the project:

dotnet new mvc -n ProductManagement --framework net8.0

The important parts of the command are:

Part Meaning
dotnet Runs the .NET command-line interface.
new Creates a project or another artifact from a template.
mvc Selects the ASP.NET Core MVC project template.
-n ProductManagement Names the project and creates a directory named ProductManagement.
--framework net8.0 Targets .NET 8.

The command creates the project files and restores the dependencies required by the application.

Checkpoint

You should now have a directory named ProductManagement inside aspnet-mvc-tutorial.

4. Enter the Project Directory

cd ProductManagement

List the generated files:

ls

You should see files and folders similar to:

ProductManagement/
├── Controllers/
├── Models/
├── Properties/
├── Views/
├── wwwroot/
├── appsettings.Development.json
├── appsettings.json
├── Program.cs
└── ProductManagement.csproj

The exact generated files can vary slightly with SDK updates, but the core MVC structure remains recognizable.

5. Open the Project in Visual Studio Code

From inside the project directory, run:

code .

The dot means the current directory. Visual Studio Code should open the ProductManagement project.

Tip

If VS Code asks whether you trust the authors of the files, review the folder path. This is a project you created locally, so you can choose the appropriate trust option.

6. Explore the MVC Project Structure

The MVC template gives us a working application before we write any code. Understanding the generated structure is more important than memorising every file.

Controllers Contains controller classes that receive requests and select responses.
Models Contains classes representing application data or related model information.
Views Contains Razor view files that generate HTML.
wwwroot Contains public static files such as CSS, JavaScript, images and libraries.
Properties Contains project launch settings used during development.
Program.cs Contains the application's startup and HTTP request-pipeline configuration.

7. The Project File

Open:

ProductManagement.csproj

A newly generated .NET 8 MVC project contains a project definition similar to:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>
Setting Meaning
Microsoft.NET.Sdk.Web Identifies the project as an ASP.NET Core web project.
net8.0 The target framework for this tutorial.
Nullable Enables nullable reference-type analysis.
ImplicitUsings Automatically includes commonly used namespaces.
Do not edit the project file yet.

We only need to recognise its purpose. Later parts will modify the project when we add Entity Framework Core and other packages.

8. Understanding Program.cs

Open Program.cs. In an ASP.NET Core application created from the web templates, this file contains the startup code that configures services and the HTTP request pipeline.

A typical .NET 8 MVC Program.cs looks like this:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

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

app.UseRouting();

app.UseAuthorization();

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

app.Run();

You do not need to memorise this code. We will return to it repeatedly as the application grows.

9. Register MVC Services and Build the Application

The first important line creates the application builder:

var builder = WebApplication.CreateBuilder(args);

The builder prepares the application configuration, logging system, dependency-injection container and other infrastructure required to create the web application.

Next:

builder.Services.AddControllersWithViews();

This registers the services needed for MVC controllers and Razor views.

Create Builder ↓ Register MVC Services ↓ Build Application

The application is then created:

var app = builder.Build();

10. The HTTP Request Pipeline

After the application is built, ASP.NET Core configures a sequence of middleware components. A request passes through this pipeline before reaching the MVC endpoint.

Browser Request ↓ HTTPS / Static Files ↓ Routing ↓ Authorization ↓ MVC Controller ↓ View ↓ HTTP Response

For example:

app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

Middleware will be explored in more detail later. For now, understand that the order of these statements is meaningful.

11. Conventional MVC Routing

The default route is configured near the bottom of Program.cs:

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

The route pattern contains three parts:

Route value Meaning
controller=Home Use HomeController when no controller is specified.
action=Index Use the Index action when no action is specified.
id? An optional route value named id.

Therefore, requesting the site's root URL normally leads to:

/ ↓ HomeController ↓ Index() ↓ Views/Home/Index.cshtml

Later, when we create a ProductsController, a URL such as /Products will naturally fit this convention.

12. Examine HomeController

Open:

Controllers/HomeController.cs

You will find a controller class containing actions such as:

public IActionResult Index()
{
    return View();
}

public IActionResult Privacy()
{
    return View();
}

An action method handles a request. Here, Index() returns a view.

We will study controllers and actions properly in Part 2. At this stage, simply recognise the connection:

URL ↓ Controller ↓ Action ↓ View

13. Examine the Default Views

Expand the Views directory.

Views/
├── Home/
│   ├── Index.cshtml
│   └── Privacy.cshtml
├── Shared/
│   ├── _Layout.cshtml
│   └── ...
├── _ViewImports.cshtml
└── _ViewStart.cshtml

The .cshtml extension identifies a Razor view file.

For the home page:

Views/Home/Index.cshtml

This file contains the content rendered when HomeController.Index() returns its default view.

14. What Is wwwroot?

The wwwroot directory is the application's web root for public static assets.

It typically contains:

  • CSS files;
  • JavaScript files;
  • images;
  • client-side libraries; and
  • other files that the browser can request directly.
wwwroot/
├── css/
├── js/
├── lib/
└── favicon.ico
Important distinction

A Razor view such as Views/Home/Index.cshtml is processed by the application. A static file under wwwroot can be served directly to the browser.

15. Build the Application

Return to the integrated terminal in VS Code and run:

dotnet build

The dotnet build command compiles the project and its dependencies.

A successful build ends with a message similar to:

Build succeeded.
    0 Warning(s)
    0 Error(s)
Checkpoint

If the build succeeds, the project is syntactically valid and can proceed to execution.

16. Run the MVC Application

Start the application:

dotnet run

dotnet run builds and runs the application from its source code. It is convenient during development because a separate manual build is not required before every run.

The terminal will display output similar to:

Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5xxx
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
Your port number may be different.

Do not copy the example port blindly. Use the exact localhost address printed by dotnet run on your computer.

17. Open the Application in a Browser

Find the line beginning with:

Now listening on:

Open the displayed URL in a browser. For example:

http://localhost:5xxx

You should see the default ASP.NET Core MVC home page.

Browser ↓ localhost ↓ ASP.NET Core ↓ HomeController ↓ Index() ↓ Index.cshtml ↓ HTML Response

18. What Is localhost?

localhost refers to the computer on which the application is currently running.

During development, your ASP.NET Core application is available through a local network address such as:

http://localhost:5000

The number after the colon is the port. Your project may use a different port.

Part Meaning
http The protocol used for the request.
localhost The local computer.
5000 An example network port.

19. Kestrel Development Server

ASP.NET Core applications use the Kestrel web server. When you run the project during development, Kestrel listens for HTTP requests at the address shown in the terminal.

Browser ↓ HTTP Request Kestrel ↓ ASP.NET Core Application ↓ MVC

In the deployment parts of this series, we will see how Kestrel can operate behind a reverse proxy in a production environment.

20. Test the Default Routes

With the application running, try these URLs using your actual localhost address:

/
/Home
/Home/Index
/Home/Privacy

The first three normally reach the home page because of the default MVC routing convention. The privacy URL invokes the Privacy action.

Observe the pattern

MVC URLs commonly correspond to /Controller/Action. The word Controller is omitted from the URL.

21. Make Your First Change

Open:

Views/Home/Index.cshtml

Replace its main content with something simple:

<div class="text-center">
    <h1 class="display-4">Product Management System</h1>
    <p>My first ASP.NET Core MVC application.</p>
</div>

Save the file.

If the application was started using only dotnet run, restart it if required and refresh the browser.

You should now see your new heading.

What just happened?

You changed a Razor view. The controller still selected the same view, but the HTML generated for the browser changed.

22. Optional: Use dotnet watch

During development, you can use:

dotnet watch

dotnet watch monitors project files for changes. Where supported, it applies Hot Reload changes or restarts the application automatically.

For beginners, both approaches are useful:

Command When to use it
dotnet run Simple, explicit run command and ideal for learning the basic workflow.
dotnet watch Convenient during repeated edit-refresh development.

23. Stop the Application

Return to the terminal where the application is running and press:

Ctrl+C

This stops the development server and returns control to the terminal.

24. The Basic Development Cycle

You have now completed the basic development cycle that will be repeated throughout the series:

Open Project ↓ Edit Code ↓ Build / Run ↓ Open Browser ↓ Test ↓ Modify ↓ Repeat

25. Hands-On Exercise

Exercise: Create and Inspect an MVC Application
  1. Go to ~/aspnet-mvc-tutorial.
  2. Confirm that the ProductManagement directory exists.
  3. Enter the project directory.
  4. Open the project in VS Code.
  5. Locate Program.cs.
  6. Locate Controllers/HomeController.cs.
  7. Locate Views/Home/Index.cshtml.
  8. Locate wwwroot.
  9. Build the project.
  10. Run the project.
  11. Open the localhost address printed by the terminal.
  12. Visit /Home/Privacy.
  13. Change the home-page heading to Product Management System.
  14. Refresh and confirm the change.
  15. Stop the application with Ctrl+C.

Suggested command sequence

cd ~
mkdir aspnet-mvc-tutorial
cd aspnet-mvc-tutorial

dotnet new mvc -n ProductManagement --framework net8.0
cd ProductManagement
code .

dotnet build
dotnet run

After testing the application:

Ctrl+C

26. Troubleshooting

dotnet: command not found

The .NET SDK is not available in the current environment or command path. Return to Part 0 and verify the .NET installation using dotnet --info.

The net8.0 framework is not available

Confirm that a .NET 8 SDK appears in dotnet --list-sdks. Installing only a newer or older runtime is not equivalent to having the .NET 8 SDK.

code: command not found

Visual Studio Code may not be installed or its command-line launcher may not be available. Verify the VS Code installation from Part 0.

The browser cannot connect

Confirm that dotnet run is still running and use the exact Now listening on: address displayed in the terminal.

The port is different from the tutorial

This is normal. Development ports can differ between projects and systems. Always use the address printed by your own application.

27. Knowledge Check

  1. Which .NET CLI template short name creates an ASP.NET Core MVC project?
  2. What does -n ProductManagement do?
  3. Why does this tutorial use --framework net8.0?
  4. Which folder contains controller classes?
  5. Which folder contains Razor views?
  6. What is the purpose of wwwroot?
  7. What is the purpose of Program.cs?
  8. What does AddControllersWithViews() register?
  9. What is the default MVC route pattern?
  10. Which controller and action handle the default home page?
  11. What does dotnet build do?
  12. What does dotnet run do?
  13. What is localhost?
  14. What is Kestrel?
  15. How do you stop a running application from the terminal?
Show suggested answers
  1. mvc.
  2. It names the project ProductManagement and creates the project directory.
  3. To ensure the course project targets .NET 8 even if newer SDKs are installed.
  4. Controllers.
  5. Views.
  6. It contains public static assets such as CSS, JavaScript and images.
  7. It configures application startup, services and the HTTP request pipeline.
  8. The services required for MVC controllers with views.
  9. {controller=Home}/{action=Index}/{id?}.
  10. HomeController.Index().
  11. It compiles the project and its dependencies.
  12. It builds and runs the application from source.
  13. The local computer on which the application is running.
  14. ASP.NET Core's cross-platform web server.
  15. Press Ctrl+C.

28. Commands Learned in Part 1

Command Purpose
dotnet new mvc -n ProductManagement --framework net8.0 Create the .NET 8 MVC project.
dotnet build Compile the project.
dotnet run Build and run the application.
dotnet watch Watch files and rerun or Hot Reload the application when supported.
Ctrl+C Stop the running development server.

29. Part 1 Summary

In this tutorial, you:

  • created an ASP.NET Core MVC application targeting .NET 8;
  • opened the project in Visual Studio Code;
  • identified the main MVC directories;
  • examined the project file;
  • reviewed Program.cs;
  • learned how MVC services and routing are configured;
  • identified the default controller and view;
  • built the application;
  • ran the application using Kestrel;
  • opened the application through localhost;
  • changed a Razor view; and
  • stopped and restarted the development server.
Browser ↓ Routing ↓ Controller ↓ Action Method ↓ View ↓ HTML Response
Next: Part 2 — Controllers, Actions and Views

In Part 2, we will create a ProductsController, add action methods, understand IActionResult, create Razor views, and use routes such as /Products and /Products/Details/1.