Skip to content

ASP.NET Core Basics — Complete Guide

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about ASP.NET Core Basics. We cover key concepts, practical examples, and best practices to help you master this topic.

Hook

ASP.NET Core is the web framework for .NET. Whether you are building a REST API, a web application, or a microservice, ASP.NET Core provides a fast, modular, and cross-platform foundation. Understanding its core concepts unlocks the ability to build production-grade web services with C#.

Learning Path

graph LR
  A[ASP.NET Core] --> B[Minimal APIs]
  A --> C[MVC Pattern]
  A --> D[Middleware]
  B --> E[Endpoint Routing]
  C --> F[Controllers]
  style A fill:#4a90d9,color:#fff
  style B fill:#4a90d9,color:#fff
  style C fill:#4a90d9,color:#fff
  style D fill:#4a90d9,color:#fff
  style E fill:#4a90d9,color:#fff
  style F fill:#4a90d9,color:#fff

Minimal APIs

Minimal APIs are the simplest way to create HTTP APIs in ASP.NET Core.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapGet("/hello/{name}", (string name) =>
    $"Hello, {name}!");

app.MapPost("/products", (Product product) =>
    Results.Created($"/products/{product.Id}", product));

app.MapPut("/products/{id}", (int id, Product product) =>
{
    // Update product
    return Results.NoContent();
});

app.MapDelete("/products/{id}", (int id) =>
{
    // Delete product
    return Results.NoContent();
});

app.Run();

public record Product(int Id, string Name, decimal Price);

MVC Pattern

The Model-View-Controller pattern separates concerns into three components.

// Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

// Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static readonly List<Product> Products = new()
    {
        new Product { Id = 1, Name = "Laptop", Price = 999.99m },
        new Product { Id = 2, Name = "Mouse", Price = 29.99m }
    };

    [HttpGet]
    public ActionResult<List<Product>> GetAll() => Ok(Products);

    [HttpGet("{id}")]
    public ActionResult<Product> GetById(int id)
    {
        var product = Products.Find(p => p.Id == id);
        if (product == null) return NotFound();
        return Ok(product);
    }

    [HttpPost]
    public ActionResult<Product> Create(Product product)
    {
        product.Id = Products.Max(p => p.Id) + 1;
        Products.Add(product);
        return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, Product updated)
    {
        var index = Products.FindIndex(p => p.Id == id);
        if (index == -1) return NotFound();
        Products[index] = updated;
        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var removed = Products.RemoveAll(p => p.Id == id);
        if (removed == 0) return NotFound();
        return NoContent();
    }
}

Middleware Pipeline

The middleware pipeline handles every HTTP request and response.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Middleware runs in the order it is added

app.Use(async (context, next) =>
{
    Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
    await next();
    Console.WriteLine($"Response: {context.Response.StatusCode}");
});

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", () => "Hello from middleware pipeline!");

app.Run();

Configuration and Services

ASP.NET Core integrates DI and configuration natively.

var builder = WebApplication.CreateBuilder(args);

// Add services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add application services
builder.Services.AddScoped<IProductRepository, InMemoryProductRepository>();
builder.Services.AddSingleton<ILoggingService, ConsoleLoggingService>();

// Configuration
string dbConnection = builder.Configuration.GetConnectionString("DefaultConnection");
bool enableCache = builder.Configuration.GetValue<bool>("FeatureFlags:UseCache");

var app = builder.Build();

// Configure pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapControllers();

app.Run();

Environment Management

ASP.NET Core uses the ASPNETCORE_ENVIRONMENT environment variable.

var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
    builder.Configuration.AddUserSecrets<Program>();
}

if (builder.Environment.IsProduction())
{
    builder.Services.AddApplicationInsightsTelemetry();
}

// The environment also determines which appsettings file is loaded:
// appsettings.{ASPNETCORE_ENVIRONMENT}.json

Common Mistakes

  1. Not using dependency injection: Inject dependencies through constructors instead of instantiating them directly in controllers.

  2. Blocking async calls: Always use async methods for database and I/O operations. Calling .Result or .Wait() causes thread pool starvation.

  3. Returning raw objects without ActionResult: Use ActionResult<T> for proper HTTP status codes and response formatting.

  4. Adding middleware in the wrong order: Middleware order matters. Authentication must come before Authorization, and Exception Handling should be early in the pipeline.

  5. Forgetting to register services: Every service injected into a controller must be registered in <a href="/design-patterns/builder/">Builder</a>.Services. Unregistered dependencies cause runtime exceptions.

Practice Questions

  1. Create a minimal API with endpoints for a todo list (CRUD operations).

  2. Build an MVC controller with [Authorize] attribute and a custom authorization policy.

  3. Write custom middleware that measures request execution time and adds it as a response header.

  4. Challenge: Implement a rate-limiting middleware that limits requests per IP address using a Sliding Window algorithm.

FAQ

What is the difference between Minimal APIs and MVC Controllers?

Minimal APIs are simpler with less boilerplate, ideal for small services and microservices. MVC Controllers provide better organization for large applications with areas, filters, and model binding.

How do I choose between .NET 8 and .NET 9?

Choose the latest stable release (currently .NET 9) for new projects. Both are Long Term Support releases.

Is ASP.NET Core suitable for high-performance scenarios?

Yes, ASP.NET Core consistently ranks among the fastest web frameworks in benchmarks like TechEmpower.

Can I host ASP.NET Core on Linux?

Yes, ASP.NET Core is fully cross-platform and runs on Linux, macOS, and Windows. It works great with Docker and Kubernetes.

How do I handle file uploads in ASP.NET Core?

Use IFormFile in controller actions or Minimal API bindings. Configure request size limits in builder.WebHost.

Mini Project: Weather API

Build a simple weather forecast API using Minimal APIs.

using System;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild",
    "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
});

app.MapGet("/weatherforecast/{days}", (int days) =>
{
    if (days < 1 || days > 14)
        return Results.BadRequest("Days must be between 1 and 14");

    var forecast = Enumerable.Range(1, days).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return Results.Ok(forecast);
});

app.Run();

public record WeatherForecast(DateOnly Date, int TemperatureC, string Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Output (when you visit /weatherforecast):

[
  {"date":"2026-06-29","temperatureC":12,"summary":"Cool","temperatureF":53},
  {"date":"2026-06-30","temperatureC":33,"summary":"Hot","temperatureF":91}
]

ASP.NET Core is the foundation of web development with C#. Whether you choose Minimal APIs for simplicity or MVC for structure, understanding the middleware pipeline, DI integration, and configuration system will serve you across all .NET web projects.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro