C# ASP.NET Core Introduction
What is ASP.NET Core?
ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, internet-connected applications. It's a redesign of the earlier ASP.NET framework, built to run on both the full .NET Framework and the cross-platform .NET Core (now simply .NET 5 and later).
Key features that make ASP.NET Core powerful include:
- Cross-platform: Runs on Windows, macOS, and Linux
- High performance: One of the fastest web frameworks available
- Dependency injection: Built-in IoC container
- Flexible deployment: Can be hosted in IIS, Nginx, Apache, Docker, or self-hosted
- Open source: Free and community-driven
- Modern: Designed with cloud-ready architecture
Prerequisites
Before diving into ASP.NET Core, you should have:
- Basic understanding of C# programming
- .NET SDK installed (download from dotnet.microsoft.com)
- A code editor (Visual Studio, VS Code with C# extensions, or JetBrains Rider)
Creating Your First ASP.NET Core Application
Let's start by creating a simple web application:
Using the Command Line
# Create a new web application
dotnet new web -n MyFirstAspNetCoreApp
# Navigate to the project directory
cd MyFirstAspNetCoreApp
# Run the application
dotnet run
After running these commands, you'll see output indicating your application is running, typically on https://localhost:5001
and http://localhost:5000
.
Project Structure Explained
A basic ASP.NET Core project contains several important files:
- Program.cs: The entry point for the application
- Startup.cs (in .NET 5 and earlier) or expanded Program.cs (in .NET 6+): Configures services and the app's request pipeline
- appsettings.json: Configuration settings
- [Project].csproj: Project file containing dependencies and configuration
Let's examine these components more closely:
Program.cs (in .NET 6+)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
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 single file contains both service configuration and middleware setup in .NET 6 and later.
Understanding ASP.NET Core Concepts
1. Middleware
Middleware are components that form a pipeline to handle requests and responses. Each middleware performs a specific function:
// Example of custom middleware
app.Use(async (context, next) =>
{
// Do something before the next middleware
Console.WriteLine("Request incoming");
await next.Invoke();
// Do something after the next middleware
Console.WriteLine("Response outgoing");
});
Common built-in middleware includes:
UseStaticFiles()
: Serves static files like CSS, JavaScript, and imagesUseRouting()
: Adds routing capabilitiesUseAuthentication()
andUseAuthorization()
: Add security featuresUseEndpoints()
: Defines endpoints for the application
2. Dependency Injection
ASP.NET Core has a built-in dependency injection (DI) container. Services are registered in the ConfigureServices
method:
// Registering services
builder.Services.AddSingleton<IMyService, MyService>();
builder.Services.AddScoped<IDataRepository, DataRepository>();
builder.Services.AddTransient<IOperationTransient, Operation>();
Service lifetimes:
- Singleton: Created once per application
- Scoped: Created once per request
- Transient: Created each time they're requested
3. Configuration
ASP.NET Core uses a flexible configuration system:
// Reading configuration values
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var apiKey = builder.Configuration["ApiKey"];
Configuration can come from multiple sources:
- appsettings.json
- Environment variables
- Command-line arguments
- User secrets (for development)
Building a Simple API
Let's create a simple REST API endpoint:
// Add this to Program.cs after other middleware
app.MapGet("/api/hello", () => new { Message = "Hello from ASP.NET Core!" });
// Add an endpoint that returns data based on input
app.MapGet("/api/greet/{name}", (string name) =>
new { Message = $"Hello, {name}! Welcome to ASP.NET Core." });
When you navigate to https://localhost:5001/api/hello
, you'll see:
{
"message": "Hello from ASP.NET Core!"
}
And https://localhost:5001/api/greet/John
will return:
{
"message": "Hello, John! Welcome to ASP.NET Core."
}
MVC Pattern in ASP.NET Core
ASP.NET Core supports the Model-View-Controller (MVC) pattern:
- Models: Represent data and business logic
- Views: Handle the UI presentation
- Controllers: Process incoming requests
Creating a Controller
using Microsoft.AspNetCore.Mvc;
namespace MyFirstAspNetCoreApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
}
}
Creating a View (Index.cshtml)
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome to ASP.NET Core</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
Real-World Example: To-Do Application
Let's build a simple To-Do application to demonstrate common ASP.NET Core patterns:
1. Create a Model
public class TodoItem
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsComplete { get; set; }
}
2. Create a Service
public interface ITodoService
{
List<TodoItem> GetAll();
TodoItem GetById(int id);
void Add(TodoItem item);
void Update(TodoItem item);
void Delete(int id);
}
public class TodoService : ITodoService
{
private readonly List<TodoItem> _items = new();
private int _nextId = 1;
public List<TodoItem> GetAll() => _items;
public TodoItem GetById(int id) => _items.FirstOrDefault(i => i.Id == id);
public void Add(TodoItem item)
{
item.Id = _nextId++;
_items.Add(item);
}
public void Update(TodoItem item)
{
var existing = GetById(item.Id);
if (existing != null)
{
existing.Title = item.Title;
existing.IsComplete = item.IsComplete;
}
}
public void Delete(int id)
{
var item = GetById(id);
if (item != null)
{
_items.Remove(item);
}
}
}
3. Register the Service
// Add this to Program.cs
builder.Services.AddSingleton<ITodoService, TodoService>();
4. Create a TodoController
[ApiController]
[Route("api/[controller]")]
public class TodoController : ControllerBase
{
private readonly ITodoService _todoService;
public TodoController(ITodoService todoService)
{
_todoService = todoService;
}
[HttpGet]
public ActionResult<IEnumerable<TodoItem>> GetAll()
{
return _todoService.GetAll();
}
[HttpGet("{id}")]
public ActionResult<TodoItem> GetById(int id)
{
var item = _todoService.GetById(id);
if (item == null)
{
return NotFound();
}
return item;
}
[HttpPost]
public ActionResult<TodoItem> Create(TodoItem item)
{
_todoService.Add(item);
return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
}
[HttpPut("{id}")]
public IActionResult Update(int id, TodoItem item)
{
if (id != item.Id)
{
return BadRequest();
}
var existingItem = _todoService.GetById(id);
if (existingItem == null)
{
return NotFound();
}
_todoService.Update(item);
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var existingItem = _todoService.GetById(id);
if (existingItem == null)
{
return NotFound();
}
_todoService.Delete(id);
return NoContent();
}
}
5. Testing the API
You can test this API using tools like Postman or curl:
# Get all todos
curl -X GET https://localhost:5001/api/todo
# Create a new todo
curl -X POST https://localhost:5001/api/todo \
-H "Content-Type: application/json" \
-d '{"title": "Learn ASP.NET Core", "isComplete": false}'
# Get a specific todo
curl -X GET https://localhost:5001/api/todo/1
# Update a todo
curl -X PUT https://localhost:5001/api/todo/1 \
-H "Content-Type: application/json" \
-d '{"id": 1, "title": "Learn ASP.NET Core", "isComplete": true}'
# Delete a todo
curl -X DELETE https://localhost:5001/api/todo/1
Summary
In this introduction to ASP.NET Core, we've covered:
- What ASP.NET Core is and its key features
- Setting up your first ASP.NET Core application
- Understanding the project structure
- Core concepts: middleware, dependency injection, and configuration
- Creating a simple API endpoint
- Building a complete To-Do application with CRUD operations
ASP.NET Core provides a robust, flexible framework for building modern web applications and APIs. From simple websites to complex microservices, ASP.NET Core offers the tools and performance needed for professional web development.
Additional Resources
- Official ASP.NET Core Documentation
- Microsoft Learn ASP.NET Core Path
- ASP.NET Core GitHub Repository
Exercises
- Create a simple weather forecast API that returns random weather data
- Add validation to the To-Do application (ensure titles are not empty)
- Create a front-end for the To-Do application using Razor Pages or MVC
- Implement persistent storage for the To-Do application using Entity Framework Core
- Add user authentication to your application using ASP.NET Core Identity
Happy coding with ASP.NET Core!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)