C# Web Development - Textnotes

C# Web Development


C# is widely used for web development using ASP.NET Core, which supports MVC, Razor Pages, APIs, and modern web patterns.

1. Introduction to ASP.NET Core

  1. ASP.NET Core is a cross-platform, open-source framework for building web apps and APIs.
  2. Key features:
  3. High performance and lightweight
  4. Cross-platform (Windows, Linux, macOS)
  5. Built-in dependency injection
  6. Supports MVC, Razor Pages, and Web APIs

2. MVC Architecture

MVC = Model-View-Controller

ComponentResponsibility
ModelRepresents data & business logic
ViewUI rendering (HTML, Razor)
ControllerHandles 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

  1. Defines how URLs map to controllers/actions.
  2. Conventional Routing

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
  1. 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

  1. 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

  1. Page-centric model, easier for simple apps.
  2. 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


<h2>@Model.Message</h2>

Summary of Chapter 14:

  1. ASP.NET Core: Modern framework for web apps & APIs.
  2. MVC Architecture: Separates concerns (Model, View, Controller).
  3. Controllers, Views, Models: Handle logic, UI, and data.
  4. Routing & Middleware: Map URLs and manage HTTP requests.
  5. Dependency Injection: Inject services for loose coupling.
  6. REST APIs: Build JSON-based services.
  7. Authentication & Authorization: Secure apps with Identity & JWT.
  8. Razor Pages: Simplified page-centric web development.