Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 30
→

ASP.NET Core Tutorial: Build Your First Web Application

ASP.NET Core Tutorial: Build Your First Web Application

October 26, 2026

Introduction

C# is widely used to develop desktop applications, APIs, enterprise software, and web applications. One of the most important technologies for building web applications with C# is ASP.NET Core.

ASP.NET Core is a modern, open-source, cross-platform web framework developed by Microsoft. It allows developers to build dynamic websites, web applications, REST APIs, and backend services using C# and .NET.

For example, you can use ASP.NET Core to build:

  • Student management systems.

  • E-commerce websites.

  • Online booking platforms.

  • Employee management portals.

  • Authentication and user account systems.

  • REST APIs for mobile and frontend applications.

In this tutorial, you will create a basic ASP.NET Core MVC application and learn how its main components work together.

1. What Is ASP.NET Core?

ASP.NET Core is a web framework for building applications that run on the .NET platform.

It supports multiple application styles, including:

  • MVC applications: Organize web applications using Models, Views, and Controllers.

  • Razor Pages: Build page-focused web applications.

  • Web APIs: Create HTTP endpoints that return data to clients.

  • Razor components and Blazor: Build interactive web user interfaces with .NET.

  • Minimal APIs: Create HTTP APIs with a lightweight endpoint-based approach.

ASP.NET Core runs on Windows, Linux, and macOS, depending on the supported .NET version and deployment environment.

ASP.NET Core vs ASP.NET Framework

ASP.NET Core ASP.NET Framework
Modern, cross-platform framework. Traditional framework primarily associated with Windows.
Actively developed as part of modern .NET. Used for existing and legacy applications.
Supports modern deployment models, including containers. Deployment options depend on the application and Windows environment.
Suitable for new web development projects. Often maintained for applications that depend on its APIs and ecosystem.

For new projects, ASP.NET Core on a supported version of .NET is generally the preferred choice.

2. Prerequisites

Before creating your first application, install the following tools:

  1. .NET SDK: Provides the tools required to build and run .NET applications.

  2. Visual Studio: An integrated development environment for C# and ASP.NET Core. Alternatively, use Visual Studio Code with suitable extensions or the .NET CLI.

  3. A web browser: Required to open and test your web application.

When using Visual Studio, select the ASP.NET and web development workload.

To check whether the .NET SDK is installed, open a terminal and run:

dotnet --version

The command displays the installed SDK version.

3. Create Your First ASP.NET Core MVC Project

You can create an MVC project using Visual Studio or the .NET CLI.

Option A: Using Visual Studio

  1. Open Visual Studio.

  2. Select Create a new project.

  3. Search for ASP.NET Core Web App (Model-View-Controller).

  4. Select the MVC template.

  5. Enter a project name such as MyFirstWebApp.

  6. Choose a supported .NET version.

  7. Create the project.

Make sure you select the MVC template rather than the Razor Pages template if you want to follow the controller-and-view examples in this tutorial.

Option B: Using the .NET CLI

Open a terminal and run:

dotnet new mvc -n MyFirstWebApp
cd MyFirstWebApp
dotnet run

The first command creates the project, the second moves into its directory, and the third builds and runs the application.

The terminal displays local addresses where the application is listening. Open the appropriate HTTPS or HTTP address in your browser.

The actual port numbers depend on your project's launch settings and runtime environment.

4. Understand the ASP.NET Core MVC Structure

An MVC project separates responsibilities into three main components: Model, View, and Controller.

<text> </text>

Model

A model represents application data and, where appropriate, its validation rules or business logic.

For example:

namespace MyFirstWebApp.Models;

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Course { get; set; } = string.Empty;
}

This model represents a student with an ID, name, and course.

View

A view defines the user interface that is rendered for the user. In ASP.NET Core MVC, views commonly use Razor syntax and .cshtml files.

Example:

@model MyFirstWebApp.Models.Student

<h1>Student Details</h1>

<p>ID: @Model.Id</p>
<p>Name: @Model.Name</p>
<p>Course: @Model.Course</p>

The @model directive specifies the type of model expected by the view. Expressions such as @Model.Name display model values.

Controller

A controller receives HTTP requests, coordinates application logic, and returns an appropriate response.

Example:

using Microsoft.AspNetCore.Mvc;
using MyFirstWebApp.Models;

namespace MyFirstWebApp.Controllers;

public class StudentController : Controller
{
    public IActionResult Details()
    {
        var student = new Student
        {
            Id = 1,
            Name = "Rahul",
            Course = "C# Programming"
        };

        return View(student);
    }
}

The Details() action creates a student object and passes it to the view.

When the application receives a request that matches this action, MVC can render the corresponding view and return the generated HTML.

5. Create Your First Controller

A controller typically contains action methods that respond to HTTP requests.

In your project, open the Controllers folder and create a file named HomeController.cs if one does not already exist.

using Microsoft.AspNetCore.Mvc;

namespace MyFirstWebApp.Controllers;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult About()
    {
        return Content("Welcome to my first ASP.NET Core application!");
    }
}

Explanation

  • HomeController is the controller class.

  • Index() is an action that returns a view.

  • About() returns a plain-text response using Content().

  • IActionResult allows an action to return different kinds of HTTP responses.

The existing MVC template usually includes a HomeController with an Index action and other sample actions. If you replace an existing controller, preserve any actions your project still needs.

6. Create a Razor View

To display HTML using MVC, create a Razor view for your action.

For the HomeController.Index() action, the default view path is:

Views/Home/Index.cshtml

Example:

@{
    ViewData["Title"] = "Home";
}

<div class="text-center">
    <h1 class="display-4">Welcome to ASP.NET Core!</h1>
    <p>Build modern web applications using C# and .NET.</p>
</div>

When the Index() action calls View(), MVC looks for the matching view by convention.

The ViewData["Title"] value can be used by the shared layout to set the page title.

What is Razor?

Razor is a markup syntax that allows C# expressions to be used inside HTML templates.

For example:

@{
    string name = "Rahul";
}

<h2>Hello, @name!</h2>

The rendered HTML displays:

<h2>Hello, Rahul!</h2>

Razor automatically HTML-encodes ordinary string expressions in typical HTML contexts. Avoid rendering untrusted content as raw HTML.

7. Understand Routing in ASP.NET Core

Routing determines which endpoint should handle an incoming HTTP request.

In a conventional MVC route, the URL often follows this pattern:

/{controller}/{action}/{id?}

For example:

  • /Home/Index can match the Index action in HomeController.

  • /Student/Details can match the Details action in StudentController.

  • /Student/Edit/5 can match an action using an optional id parameter, if the route and action support it.

In the standard MVC template, routing is typically configured in Program.cs.

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

Here:

  • controller=Home sets the default controller.

  • action=Index sets the default action.

  • {id?} defines an optional route parameter.

This configuration allows the root URL / to map to HomeController.Index().

8. Understand Program.cs and the Middleware Pipeline

In modern ASP.NET Core projects, Program.cs configures services and the HTTP request pipeline.

A simplified MVC application might look 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();

This example assumes that the project contains the referenced error action and required supporting configuration. The default MVC template may include additional middleware or configuration.

Important components

  • WebApplication.CreateBuilder(args) initializes the application builder.

  • AddControllersWithViews() registers MVC controller and view services.

  • UseHttpsRedirection() redirects HTTP requests to HTTPS when configured.

  • UseStaticFiles() enables serving static assets such as CSS, JavaScript, and images from the web root.

  • UseRouting() enables endpoint routing.

  • UseAuthorization() adds authorization middleware.

  • MapControllerRoute() maps conventional MVC routes.

  • Run() starts the application.

Middleware components process HTTP requests and responses in the configured pipeline order. Their order can affect application behavior.

9. Pass Data from a Controller to a View

Controllers frequently pass data to views. ASP.NET Core MVC provides multiple approaches, including strongly typed models, ViewData, and ViewBag.

Using ViewData

public IActionResult Welcome()
{
    ViewData["Message"] = "Welcome to C# web development!";
    return View();
}

In Views/Home/Welcome.cshtml:

<h1>@ViewData["Message"]</h1>

Using ViewBag

public IActionResult Greeting()
{
    ViewBag.Name = "Rahul";
    return View();
}

In Views/Home/Greeting.cshtml:

<h1>Hello, @ViewBag.Name!</h1>

Using a strongly typed model

For more structured data, a strongly typed view model is usually preferable because it provides compile-time type checking and better tooling support.

Use ViewData and ViewBag for suitable small cases, but prefer models when passing structured application data.

10. Create a Form in ASP.NET Core MVC

Forms allow users to submit information, such as a name, email address, or search term.

For this example, create a simple form that collects a user's name.

Step 1: Create a model

Create Models/ContactForm.cs:

using System.ComponentModel.DataAnnotations;

namespace MyFirstWebApp.Models;

public class ContactForm
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; } = string.Empty;
}

The validation attributes specify that the name is required and cannot exceed 100 characters.

Step 2: Create controller actions

Add these actions to a controller:

using Microsoft.AspNetCore.Mvc;
using MyFirstWebApp.Models;

public IActionResult Contact()
{
    return View(new ContactForm());
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Contact(ContactForm model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    ViewBag.Message = $"Thank you, {model.Name}!";
    return View(new ContactForm());
}

Place these actions inside a controller class that inherits from Controller, and include the appropriate namespace declarations for your project.

The GET action displays the form. The POST action processes the submitted model, checks validation, and returns a response.

Step 3: Create the view

Create Views/Home/Contact.cshtml if these actions belong to HomeController.

@model MyFirstWebApp.Models.ContactForm

<h1>Contact Form</h1>

@if (ViewBag.Message != null)
{
    <p>@ViewBag.Message</p>
}

<form asp-action="Contact" method="post">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>

    <button type="submit">Submit</button>
</form>

This view uses MVC tag helpers to generate form-related HTML. The shared layout or view should have the standard MVC tag-helper configuration, commonly provided by _ViewImports.cshtml.

For client-side validation, configure the validation scripts used by your project. Server-side validation must still be performed.

11. What Is Dependency Injection?

Dependency injection (DI) is a design technique that provides a class with the dependencies it needs rather than making the class construct every dependency itself.

ASP.NET Core includes a built-in dependency injection container.

For example, you can register a service in Program.cs:

builder.Services.AddScoped<IMessageService, MessageService>();

The application must define the IMessageService interface and MessageService implementation.

A controller can then request the service through its constructor:

public class HomeController : Controller
{
    private readonly IMessageService _messageService;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    public IActionResult About()
    {
        return Content(_messageService.GetMessage());
    }
}

This example assumes IMessageService and MessageService are defined and registered correctly.

Dependency injection helps separate responsibilities, improve testability, and make application components easier to maintain.

12. Connect ASP.NET Core to a Database

Many web applications need to persist data. ASP.NET Core can work with SQL Server through ADO.NET, Entity Framework Core, or other data-access libraries.

For example, an application might use Entity Framework Core to retrieve products from a database or use ADO.NET for direct SQL queries.

A common application architecture separates responsibilities into layers:

  • Controller: Receives HTTP requests and returns responses.

  • Service: Contains application or business logic.

  • Data-access layer: Reads and writes data.

  • Database: Stores persistent information.

For a real project, avoid putting every database operation directly inside controller actions. Separating application logic and data access generally improves maintainability and testability.

The next tutorial in this course covers Entity Framework Core in greater detail.

13. Common ASP.NET Core Errors

Error 1: The application does not start

Possible causes include an unsupported SDK, an invalid project configuration, or a port conflict.

What to do: Read the terminal output, verify the installed SDK, and check the project's launch settings.

Error 2: HTTP 404 — Not Found

The requested URL may not match a configured route or endpoint.

What to do: Check the controller name, action name, route configuration, and URL.

Error 3: The view cannot be found

MVC normally searches for a view matching the controller and action conventions.

What to do: Verify the view is in the expected folder, such as Views/Home/Index.cshtml, and that its filename matches the action.

Error 4: Form validation does not work as expected

The model may not contain validation attributes, or the action may not check ModelState.IsValid.

What to do: Verify the model, POST action, validation attributes, and relevant client-side scripts.

Error 5: Static CSS or JavaScript files do not load

The files may be in the wrong directory or static-file middleware may be missing.

What to do: Check the wwwroot directory, asset paths, and the application's static-file configuration.

14. ASP.NET Core Best Practices

Follow these practices when building web applications:

  1. Use a supported .NET release.

  2. Separate controllers, views, models, and services according to their responsibilities.

  3. Validate user input on the server.

  4. Use parameterized SQL or a suitable ORM for database access.

  5. Store connection strings and secrets securely.

  6. Use dependency injection to manage service dependencies.

  7. Protect state-changing forms against cross-site request forgery (CSRF), using the framework's anti-forgery features where appropriate.

  8. Handle exceptions and log useful diagnostic information securely.

  9. Use HTTPS in deployed environments.

  10. Apply authentication and authorization when the application requires user accounts or restricted resources.

  11. Avoid placing business logic directly in Razor views.

  12. Test controller behavior, service logic, and important application workflows.

15. Practical Project: Student Management Web Application

Build a basic student management website using ASP.NET Core MVC.

Project features

  • Display a list of students.

  • View student details.

  • Add new students.

  • Edit student information.

  • Delete student records.

  • Validate submitted form data.

  • Store records in a SQL Server database.

  • Show helpful messages when operations succeed or fail.

Suggested development steps

  1. Create an ASP.NET Core MVC project.

  2. Define a Student model and validation rules.

  3. Create a StudentController.

  4. Add views for listing, creating, editing, and viewing students.

  5. Configure database access.

  6. Add the necessary CRUD operations.

  7. Validate input and handle errors.

  8. Test the application in a browser.

Challenge: Add a search field to filter students by name and a course filter to narrow the displayed records.

16. Quick Quiz

Q1. What is ASP.NET Core?

A. A programming language
B. A modern web framework for .NET
C. A database server
D. A CSS library

Q2. What does MVC stand for?

A. Model, View, Controller
B. Main, Variable, Class
C. Method, Value, Code
D. Model, Version, Compiler

Q3. Which file commonly contains application startup and middleware configuration in modern ASP.NET Core projects?

A. Program.cs
B. style.css
C. index.html
D. package.json

Q4. What is the purpose of routing?

A. To format CSS files
B. To match incoming requests to endpoints
C. To create database tables automatically
D. To compile images

Q5. What does dependency injection help achieve?

A. It removes the need for C#
B. It provides dependencies to classes and supports separation of concerns
C. It automatically fixes all errors
D. It replaces HTTP

Quiz Answers

  1. B — A modern web framework for .NET.

  2. A — Model, View, Controller.

  3. A — Program.cs.

  4. B — Matching incoming requests to endpoints.

  5. B — Providing dependencies and supporting separation of concerns.

17. Frequently Asked Questions

What is ASP.NET Core used for?

ASP.NET Core is used to build websites, MVC applications, Razor Pages applications, REST APIs, and other HTTP-based services with .NET.

Is ASP.NET Core free?

ASP.NET Core is open-source and available for use under its applicable license. Some development tools, hosting services, or third-party components may have separate licensing or costs.

Do I need to know C# before learning ASP.NET Core?

Basic knowledge of C# is strongly recommended. Understanding classes, methods, properties, interfaces, and object-oriented programming makes it easier to learn web development with ASP.NET Core.

What is the difference between MVC and Razor Pages?

MVC organizes web applications around models, controllers, and views. Razor Pages uses a page-focused structure in which page handlers and page models manage requests. Both are supported by ASP.NET Core.

Can ASP.NET Core connect to SQL Server?

Yes. ASP.NET Core can connect to SQL Server through data-access technologies such as ADO.NET and Entity Framework Core.

What is Razor syntax?

Razor is a syntax that combines HTML markup with C# expressions in .cshtml templates and other supported Razor files.

What is dependency injection in ASP.NET Core?

Dependency injection provides application components with the services they depend on. ASP.NET Core includes a built-in container for registering and resolving these services.

Can ASP.NET Core run on Linux?

Yes. ASP.NET Core applications can run on supported Linux environments as well as Windows and macOS, depending on the target .NET version and deployment requirements.

Conclusion

ASP.NET Core provides a flexible platform for building modern web applications using C# and .NET. By learning project setup, MVC architecture, routing, controllers, Razor views, form handling, and dependency injection, you can begin developing structured web applications.

Practise the examples, explore the generated MVC project, and build the Student Management Web Application to strengthen your understanding.

←
Post 28 of 30
→