ASP.NET Framework

Introduction to ASP.NET

ASP.NET is a web development framework created by Microsoft that enables developers to build modern, cloud-based, and internet-connected applications.

Framework Variants:

  • ASP.NET Core (Cross-platform, open-source)
  • ASP.NET Framework (Windows-only, legacy)
  • Blazor (Client-side web UI with C#)

Key Benefits:

  • High performance and scalability
  • Cross-platform development
  • Built-in dependency injection
  • Robust security features
  • Extensive tooling support

Core Concepts

Middleware

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}

Dependency Injection

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext();
    services.AddScoped();
    services.AddSingleton();
}

Configuration

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=True;"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        }
    }
}

MVC Pattern

Controllers

public class HomeController : Controller
{
    private readonly ILogger _logger;
    
    public HomeController(ILogger logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create(ProductModel model)
    {
        if (ModelState.IsValid)
        {
            // Process the model
            return RedirectToAction(nameof(Index));
        }
        return View(model);
    }
}

Models

public class ProductModel
{
    [Required]
    public string Name { get; set; }
    
    [Range(0, 1000)]
    public decimal Price { get; set; }
    
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
}

Views

@model ProductModel

Razor Pages

Page Model

public class IndexModel : PageModel
{
    private readonly ApplicationDbContext _context;
    
    public IndexModel(ApplicationDbContext context)
    {
        _context = context;
    }
    
    public IList Products { get; set; }
    
    public async Task OnGetAsync()
    {
        Products = await _context.Products.ToListAsync();
    }
}

Razor Page

@page
@model IndexModel

Products

@foreach (var item in Model.Products) { }
Name Price Actions
@item.Name @item.Price.ToString("C") Edit

Web API Development

API Controllers

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _service;
    
    public ProductsController(IProductService service)
    {
        _service = service;
    }
    
    [HttpGet]
    public async Task>> Get()
    {
        var products = await _service.GetAllAsync();
        return Ok(products);
    }
    
    [HttpPost]
    public async Task> Create(ProductDto dto)
    {
        var product = await _service.CreateAsync(dto);
        return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
    }
}

API Documentation

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo 
        { 
            Title = "My API", 
            Version = "v1" 
        });
    });
}

Data Access with Entity Framework

DbContext

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions options)
        : base(options)
    {
    }
    
    public DbSet Products { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .Property(p => p.Price)
            .HasColumnType("decimal(18,2)");
    }
}

Migrations

# Add Migration
dotnet ef migrations add InitialCreate

# Update Database
dotnet ef database update

# Generate SQL Script
dotnet ef migrations script

Security and Authentication

Identity Setup

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity()
        .AddEntityFrameworkStores()
        .AddDefaultTokenProviders();
        
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => 
        {
            // Configure JWT parameters
        });
}

Authorization

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    [Authorize(Policy = "RequireManagerRole")]
    public IActionResult ManageUsers()
    {
        return View();
    }
}

Deployment and Hosting

Deployment Options:

  • Azure App Service
  • IIS Server
  • Docker Containers
  • Linux Servers

Docker Support

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["MyApp.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet build -c Release -o /app/build

FROM build AS publish
RUN dotnet publish -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]