1. Introduction to ASP.NET Core
- ASP.NET Core is a cross-platform, open-source framework for building web apps and APIs.
- Key features:
- High performance and lightweight
- Cross-platform (Windows, Linux, macOS)
- Built-in dependency injection
- Supports MVC, Razor Pages, and Web APIs
2. MVC Architecture
MVC = Model-View-Controller
| ComponentResponsibility |
| Model | Represents data & business logic |
| View | UI rendering (HTML, Razor) |
| Controller | Handles HTTP requests & responses |
3. Controllers, Views, Models
3.1 Model
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
3.2 Controller
using Microsoft.AspNetCore.Mvc;
public class StudentController : Controller
{
public IActionResult Index()
{
var students = new List<Student>
{
new Student { Id = 1, Name = "John", Age = 20 },
new Student { Id = 2, Name = "Alice", Age = 22 }
};
return View(students);
}
}
3.3 View (Razor)
Views/Student/Index.cshtml
@model IEnumerable<Student>
<h2>Students List</h2>
<ul>
@foreach(var s in Model)
{
<li>@s.Name - @s.Age</li>
}
</ul>
4. Routing
- Defines how URLs map to controllers/actions.
- Conventional Routing
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
- Attribute Routing
[Route("students/{id}")]
public IActionResult Details(int id) { ... }
5. Middleware
Middleware components handle HTTP request/response pipeline.
app.Use(async (context, next) =>
{
Console.WriteLine("Request Incoming");
await next();
Console.WriteLine("Response Outgoing");
});
app.UseStaticFiles();
app.UseRouting();
Common middleware: Logging, Authentication, CORS, Error Handling.
6. Dependency Injection (DI)
ASP.NET Core has built-in DI to inject services.
// Service
public interface IMessageService { string GetMessage(); }
public class MessageService : IMessageService
{
public string GetMessage() => "Hello from DI";
}
// Register service
builder.Services.AddScoped<IMessageService, MessageService>();
// Inject in Controller
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Index()
{
ViewBag.Message = _messageService.GetMessage();
return View();
}
}
7. REST API Development
Controller Example
[ApiController]
[Route("api/[controller]")]
public class StudentApiController : ControllerBase
{
private static List<Student> students = new()
{
new Student { Id = 1, Name = "John", Age = 20 },
new Student { Id = 2, Name = "Alice", Age = 22 }
};
[HttpGet]
public IActionResult GetAll() => Ok(students);
[HttpGet("{id}")]
public IActionResult Get(int id) => Ok(students.FirstOrDefault(s => s.Id == id));
[HttpPost]
public IActionResult Create(Student student)
{
students.Add(student);
return CreatedAtAction(nameof(Get), new { id = student.Id }, student);
}
}
8. Authentication & Authorization
8.1 Identity Framework
- Built-in user management for login, registration, roles.
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
8.2 JWT Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
};
});
9. Razor Pages
- Page-centric model, easier for simple apps.
- Combines Page Model (C#) and Razor view (HTML).
Pages/Index.cshtml.cs
public class IndexModel : PageModel
{
public string Message { get; private set; }
public void OnGet()
{
Message = "Welcome to Razor Pages!";
}
}
Pages/Index.cshtml
Summary of Chapter 14:
- ASP.NET Core: Modern framework for web apps & APIs.
- MVC Architecture: Separates concerns (Model, View, Controller).
- Controllers, Views, Models: Handle logic, UI, and data.
- Routing & Middleware: Map URLs and manage HTTP requests.
- Dependency Injection: Inject services for loose coupling.
- REST APIs: Build JSON-based services.
- Authentication & Authorization: Secure apps with Identity & JWT.
- Razor Pages: Simplified page-centric web development.