ASP.NET Core  

ASP.NET Core — Concept Overview

1. ASP.NET Core Overview

Concept
ASP.NET Core is a cross-platform, open-source framework for building web applications, APIs, and microservices.

Real Example:
Creating a website that works on Windows, Linux, or macOS using one codebase.

2. Project Structure

Concept:
An ASP.NET Core project includes:

  • Program.cs → Main startup logic (replaces Global.asax)

  • appsettings.json → Configuration

  • Controllers, Models, Views → MVC structure

  • wwwroot → Static files (CSS, JS, images)

Example
wwwroot/css/site.css for styles, Controllers/HomeController.cs for logic.

3. Middleware Pipeline

Concept
Middleware are components executed in sequence to handle HTTP requests and responses.

Example
A request passes through middleware for Logging → Authentication → Routing → Response.

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

4. Routing

Concept
Determines how URLs map to controllers and actions.

Example
URL /product/details/5 maps to:

[Route("product/details/{id}")]
public IActionResult Details(int id)

5. MVC Pattern

Concept
Model–View–Controller separates logic:

  • Model → Data structure

  • View → UI (HTML + Razor)

  • Controller → Handles user requests

Example
TaskController → Controls all task operations.
Task.cs → Holds task data.
Index.cshtml → Displays task list.

6. Dependency Injection (DI)

Concept
ASP.NET Core provides built-in DI to manage object lifetimes and dependencies.

Example

builder.Services.AddScoped<ITaskService, TaskService>();

Then inject into controller:

public class TaskController : Controller
{
    private readonly ITaskService _taskService;
    public TaskController(ITaskService taskService)
    {
        _taskService = taskService;
    }
}

7. Entity Framework Core (EF Core)

Concept
ORM (Object-Relational Mapper) that lets you interact with the database using C# classes instead of SQL.

Example

_context.Tasks.Add(new TaskItem { Title = "Fix Bug" });
await _context.SaveChangesAsync();

8. Configuration & Settings

Concept
All settings stored in appsettings.json — database strings, keys, URLs, etc.

Example

"ConnectionStrings": {
  "DefaultConnection": "Server=.;Database=TaskDB;Trusted_Connection=True;"
}

9. Authentication & Authorization

Concept

  • Authentication: Verify who the user is

  • Authorization: Verify what they can access

Example

[Authorize(Roles="Admin")]
public IActionResult AdminPage() { ... }

10. Identity Framework

Concept
ASP.NET Core Identity provides login, registration, roles, and claims management.

Example
Built-in login pages using scaffolding:

dotnet aspnet-codegenerator identity -dc AppDbContext

11. Razor Pages & Razor Syntax

Concept
Razor = combination of HTML + C# for generating dynamic views.

Example

<p>Hello, @User.Identity.Name!</p>

12. Model Binding & Validation

Concept
Automatically maps form data to model objects and validates them.

Example

public class TaskModel
{
    [Required]
    public string Title { get; set; }
}

13. Filters

Concept
Filters run before or after actions (for logging, authorization, etc.)

Example

public class LogActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        Console.WriteLine("Action starting...");
    }
}

14. Tag Helpers

Concept
Enhance Razor markup with server-side logic.

Example

<form asp-controller="Task" asp-action="Create">

15. Web API & JSON

Concept
Build RESTful APIs to send/receive JSON.

Example

[HttpGet("api/tasks")]
public IEnumerable<TaskItem> GetTasks() => _context.Tasks.ToList();

16. SignalR (Real-Time Communication)

Concept
For chat, notifications, dashboards, etc.

Example
Notify users instantly when a task is created:

await _hubContext.Clients.All.SendAsync("TaskAdded", task.Title);

17. Middleware Customization

Concept
Create your own middleware to intercept requests.

Example

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

18. Background Tasks / Hosted Services

Concept
Run background jobs in the same application (like email sending, cleanup, etc.)

Example

public class ReminderService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // check pending tasks
            await Task.Delay(60000);
        }
    }
}

19. Logging

Concept
ASP.NET Core uses built-in logging (Console, File, Serilog, etc.)

Example

private readonly ILogger<HomeController> _logger;
_logger.LogInformation("User visited home page");

20. Deployment

Concept
Publish and host apps using:

  • IIS (Windows)

  • Kestrel (built-in)

  • Docker / Azure

Command

dotnet publish -c Release

21. Advanced Concepts

ConceptDescription
CachingImprove performance using Memory or Distributed cache
LocalizationMulti-language app
gRPC / Minimal APIsLightweight APIs
Health ChecksMonitor API and service status
Configuration ProvidersLoad config from JSON, ENV, DB
Unit Testing (xUnit/NUnit)Test controllers, services
Swagger (OpenAPI)Document Web APIs

Real-Time Example Summary

ConceptReal Example
MVCBuilding a “Task Management” app
EF CoreStoring tasks in SQL Server
DIInjecting services like TaskService
MiddlewareCustom logging of every request
IdentityAdmin/User login system
SignalRReal-time “task raised” notification
Background TaskSend reminder emails
APIMobile integration for tasks