.NET ASP.NET Introduction
What is ASP.NET?
ASP.NET is Microsoft's web development framework that enables developers to build dynamic web applications, web services, and websites. It's part of the larger .NET platform and provides a powerful, feature-rich environment for creating modern web solutions.
ASP.NET has evolved significantly over the years, with several versions and implementations:
- ASP.NET Web Forms: The original ASP.NET implementation that uses a desktop-like event-driven model
- ASP.NET MVC: A Model-View-Controller implementation that offers more control over HTML and better separation of concerns
- ASP.NET Web API: Focused on building HTTP services for a wide range of clients
- ASP.NET Core: The modern, cross-platform, high-performance version of ASP.NET
In this introduction, we'll focus primarily on ASP.NET Core, the latest and recommended version for new development.
Why Learn ASP.NET?
Here are some compelling reasons to learn ASP.NET:
- Enterprise adoption: Widely used in enterprise environments
- Robust ecosystem: Extensive libraries, tools, and community support
- Integration: Seamless integration with other Microsoft technologies
- Performance: ASP.NET Core is one of the fastest web frameworks available
- Cross-platform: ASP.NET Core runs on Windows, Linux, and macOS
- Modern development: Supports modern web development practices and patterns
Prerequisites
Before diving into ASP.NET, you should have:
- Basic understanding of C# programming language
- Familiarity with HTML, CSS, and JavaScript fundamentals
- .NET SDK installed on your computer
- A code editor (Visual Studio, VS Code with C# extensions, or JetBrains Rider)
Setting Up Your Development Environment
To start developing ASP.NET applications, you'll need:
-
Install the .NET SDK: Download and install from dotnet.microsoft.com
-
Choose an IDE:
- Visual Studio (comprehensive IDE with built-in ASP.NET templates)
- Visual Studio Code with C# extensions (lighter option)
- JetBrains Rider (powerful alternative IDE)
-
Verify installation by opening a terminal/command prompt and typing:
dotnet --version
You should see the version number of your installed .NET SDK.
ASP.NET Core Architecture
ASP.NET Core follows a modular architecture built around these key concepts:
1. Middleware
Middleware components form a pipeline that handles requests and responses. Each component can:
- Process incoming requests
- Pass control to the next middleware
- Process outgoing responses
2. Dependency Injection
ASP.NET Core includes a built-in dependency injection (DI) container that makes it easy to:
- Manage service lifetimes
- Decouple components
- Improve testability
3. Configuration
A flexible configuration system that can load settings from:
- JSON files
- Environment variables
- Command-line arguments
- And more
4. Hosting Model
ASP.NET Core applications are console applications that create a web server in their Main
method.
Creating Your First ASP.NET Core Web Application
Let's create a simple ASP.NET Core web application:
Step 1: Create a New Project
Open a terminal or command prompt and run:
dotnet new webapp -n MyFirstAspNetApp
cd MyFirstAspNetApp
This creates a new ASP.NET Core web application with Razor Pages (a page-based programming model).
Step 2: Explore the Project Structure
Your new project contains several important files:
- Program.cs: Application entry point and configuration
- appsettings.json: Application configuration settings
- wwwroot/: Static files (CSS, JavaScript, images)
- Pages/: Razor Pages for the UI
Step 3: Understanding Program.cs
The Program.cs
file is where your application starts. In ASP.NET Core 6.0+, it has a simplified structure:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
This code:
- Creates a web application builder
- Registers services with the dependency injection system
- Builds the app and configures the middleware pipeline
- Starts the web server
Step 4: Run Your Application
Execute the application with:
dotnet run
Open a browser and navigate to https://localhost:5001
(or the URL displayed in your terminal). You should see the default ASP.NET Core welcome page.
ASP.NET Core Application Models
ASP.NET Core supports multiple programming models:
Razor Pages
A page-based model that pairs HTML markup with C# code. Great for simpler scenarios and beginners.
Example Razor Page (Index.cshtml
):
@page
@model IndexModel
@{
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>
<p>Current time: @DateTime.Now</p>
</div>
MVC (Model-View-Controller)
A pattern that separates an application into three main components:
- Models: Data and business logic
- Views: User interface
- Controllers: Handle requests and responses
To create an MVC project:
dotnet new mvc -n MyMvcApp
Example Controller:
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
}
Blazor
A framework for building interactive client-side web UI with .NET:
- Blazor Server: Runs server-side with SignalR connection
- Blazor WebAssembly: Runs directly in the browser using WebAssembly
Web API
For building HTTP services that can be consumed by various clients:
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Building a Simple Data-Driven ASP.NET Core App
Let's build a simple todo list application to illustrate key ASP.NET concepts:
Step 1: Create a Model
Create a Models
folder and add a TodoItem.cs
file:
public class TodoItem
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsComplete { get; set; }
}
Step 2: Create a Service
Create a Services
folder and add ITodoService.cs
and TodoService.cs
:
public interface ITodoService
{
List<TodoItem> GetAllItems();
TodoItem GetById(int id);
void Add(TodoItem item);
void Update(TodoItem item);
void Delete(int id);
}
public class TodoService : ITodoService
{
private List<TodoItem> _todos = new List<TodoItem>
{
new TodoItem { Id = 1, Title = "Learn ASP.NET Core", IsComplete = false },
new TodoItem { Id = 2, Title = "Build a web app", IsComplete = false },
new TodoItem { Id = 3, Title = "Deploy to production", IsComplete = false }
};
public List<TodoItem> GetAllItems() => _todos;
public TodoItem GetById(int id) => _todos.FirstOrDefault(t => t.Id == id);
public void Add(TodoItem item)
{
item.Id = _todos.Max(t => t.Id) + 1;
_todos.Add(item);
}
public void Update(TodoItem item)
{
var existingItem = GetById(item.Id);
if (existingItem != null)
{
existingItem.Title = item.Title;
existingItem.IsComplete = item.IsComplete;
}
}
public void Delete(int id)
{
var item = GetById(id);
if (item != null)
{
_todos.Remove(item);
}
}
}
Step 3: Register the Service
Update Program.cs
to register the todo service:
// Add services to the container
builder.Services.AddRazorPages();
builder.Services.AddSingleton<ITodoService, TodoService>();
Step 4: Create a Razor Page
Create a new Razor Page called Todos.cshtml
in the Pages folder:
@page
@model TodosModel
@{
ViewData["Title"] = "Todo List";
}
<h1>Todo List</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.TodoItems)
{
<tr>
<td>@item.Id</td>
<td>@item.Title</td>
<td>@(item.IsComplete ? "Completed" : "Pending")</td>
</tr>
}
</tbody>
</table>
And the corresponding code-behind file (Todos.cshtml.cs
):
using Microsoft.AspNetCore.Mvc.RazorPages;
using MyFirstAspNetApp.Models;
using MyFirstAspNetApp.Services;
public class TodosModel : PageModel
{
private readonly ITodoService _todoService;
public List<TodoItem> TodoItems { get; set; }
public TodosModel(ITodoService todoService)
{
_todoService = todoService;
}
public void OnGet()
{
TodoItems = _todoService.GetAllItems();
}
}
Common ASP.NET Core Concepts
Middleware
Middleware forms a pipeline to handle requests and responses. Common middleware includes:
// Error handling
app.UseExceptionHandler("/Error");
// Static files (CSS, JS, images)
app.UseStaticFiles();
// Routing
app.UseRouting();
// Authentication and Authorization
app.UseAuthentication();
app.UseAuthorization();
// Endpoint execution
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
Configuration
ASP.NET Core uses a flexible configuration system:
// Read configuration from appsettings.json
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var apiKey = builder.Configuration["ApiKeys:MyServiceKey"];
// Read from environment variables
var environmentSetting = builder.Configuration["ENVIRONMENT_VARIABLE_NAME"];
Dependency Injection
Services are registered with different lifetimes:
// Transient: New instance created each time requested
builder.Services.AddTransient<ITransientService, TransientService>();
// Scoped: New instance created once per request
builder.Services.AddScoped<IScopedService, ScopedService>();
// Singleton: One instance for the entire application
builder.Services.AddSingleton<ISingletonService, SingletonService>();
And consumed via constructor injection:
public class MyController : Controller
{
private readonly IScopedService _scopedService;
public MyController(IScopedService scopedService)
{
_scopedService = scopedService;
}
public IActionResult Index()
{
// Use the service
_scopedService.DoSomething();
return View();
}
}
Real-World Application: A Contact Management System
Let's look at a more practical example - a simple contact management system:
1. Define Contact Model
public class Contact
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
[Phone]
public string PhoneNumber { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
}
2. Set up Entity Framework Core
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Contact> Contacts { get; set; }
}
// In Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
3. Create a Repository
public interface IContactRepository
{
Task<List<Contact>> GetAllAsync();
Task<Contact> GetByIdAsync(int id);
Task AddAsync(Contact contact);
Task UpdateAsync(Contact contact);
Task DeleteAsync(int id);
}
public class ContactRepository : IContactRepository
{
private readonly ApplicationDbContext _context;
public ContactRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<List<Contact>> GetAllAsync()
{
return await _context.Contacts.ToListAsync();
}
public async Task<Contact> GetByIdAsync(int id)
{
return await _context.Contacts.FindAsync(id);
}
public async Task AddAsync(Contact contact)
{
_context.Contacts.Add(contact);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(Contact contact)
{
_context.Entry(contact).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var contact = await _context.Contacts.FindAsync(id);
if (contact != null)
{
_context.Contacts.Remove(contact);
await _context.SaveChangesAsync();
}
}
}
// Register in Program.cs
builder.Services.AddScoped<IContactRepository, ContactRepository>();
4. Create a Controller (for MVC or API)
[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
private readonly IContactRepository _repository;
public ContactsController(IContactRepository repository)
{
_repository = repository;
}
// GET: api/Contacts
[HttpGet]
public async Task<ActionResult<IEnumerable<Contact>>> GetContacts()
{
return await _repository.GetAllAsync();
}
// GET: api/Contacts/5
[HttpGet("{id}")]
public async Task<ActionResult<Contact>> GetContact(int id)
{
var contact = await _repository.GetByIdAsync(id);
if (contact == null)
{
return NotFound();
}
return contact;
}
// POST: api/Contacts
[HttpPost]
public async Task<ActionResult<Contact>> PostContact(Contact contact)
{
await _repository.AddAsync(contact);
return CreatedAtAction(nameof(GetContact), new { id = contact.Id }, contact);
}
// PUT: api/Contacts/5
[HttpPut("{id}")]
public async Task<IActionResult> PutContact(int id, Contact contact)
{
if (id != contact.Id)
{
return BadRequest();
}
await _repository.UpdateAsync(contact);
return NoContent();
}
// DELETE: api/Contacts/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteContact(int id)
{
await _repository.DeleteAsync(id);
return NoContent();
}
}
Summary
In this introduction to ASP.NET, we've covered:
- What ASP.NET is and why it's a valuable skill
- Setting up your development environment
- The core architecture and components of ASP.NET
- Creating your first web application
- Different application models (Razor Pages, MVC, Blazor, Web API)
- Essential concepts: middleware, dependency injection, and configuration
- Building a simple CRUD application
ASP.NET Core provides a robust platform for building modern web applications with performance, security, and scalability in mind. As you continue your journey, you'll discover its extensive features for authentication, caching, real-time communication with SignalR, and much more.
Additional Resources
Documentation and Learning
Tools
Practice Exercises
- Todo App Enhancement: Add create, update, and delete functionality to the todo list example from this guide.
- Blog Application: Create a simple blog with posts and comments.
- API with Authentication: Build a Web API with JWT authentication.
- Real-time Chat: Implement a chat application using SignalR.
- Integration with Database: Connect your application to SQL Server, PostgreSQL, or SQLite.
Remember that ASP.NET development is a journey - start with small projects and gradually take on more complex challenges as you build your skills!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)