logo
eng-flag

ASP.NET Cheatsheet

Table of Contents

  1. ASP.NET Basics
  2. ASP.NET Core
  3. MVC Pattern
  4. Routing
  5. Controllers and Actions
  6. Views and Razor Syntax
  7. Models and Data Binding
  8. Entity Framework Core
  9. Dependency Injection
  10. Middleware
  11. Authentication and Authorization
  12. Web API
  13. Testing
  14. Deployment
  15. Best Practices

ASP.NET Basics

What is ASP.NET?

ASP.NET is a free, open-source web application framework developed by Microsoft. It's used to build dynamic websites, web applications, and web services.

Key Features

  • Cross-platform
  • High-performance
  • Open-source
  • Modern, component-based architecture

Creating an ASP.NET Project

You can create an ASP.NET project using:

  1. Visual Studio
  2. Visual Studio Code with .NET CLI
  3. .NET CLI alone

Example using .NET CLI:

dotnet new webapp -n MyAspNetProject
cd MyAspNetProject
dotnet run

ASP.NET Core

ASP.NET Core is the cross-platform, high-performance evolution of ASP.NET.

Program.cs

The entry point for an ASP.NET Core application:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs

Configure services and the app's request pipeline:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

MVC Pattern

ASP.NET Core MVC is a design pattern for achieving separation of concerns.

  • Model: Represents the data and business logic
  • View: Handles the UI and presentation
  • Controller: Manages user requests and responses

Routing

Routing is the process of matching incoming HTTP requests to controller actions.

Conventional Routing

Set up in Startup.cs:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Attribute Routing

Applied directly to controller actions:

[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        // Action method implementation
    }
}

Controllers and Actions

Controllers handle incoming requests and return responses to the client.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
        return View();
    }

    [HttpPost]
    public IActionResult Contact(ContactViewModel model)
    {
        if (ModelState.IsValid)
        {
            // Process the contact form
            return RedirectToAction("ThankYou");
        }
        return View(model);
    }
}

Views and Razor Syntax

Views are responsible for presenting content to the user. Razor is a markup syntax for embedding server-based code into webpages.

Razor Syntax Examples

@{
    ViewData["Title"] = "Home Page";
}

<h1>Welcome to my site, @User.Identity.Name!</h1>

@if (User.IsInRole("Admin"))
{
    <p>You are an admin.</p>
}

<ul>
@foreach (var item in Model)
{
    <li>@item.Name</li>
}
</ul>

Models and Data Binding

Models represent the data of the application. Data binding is the process of mapping HTTP request data to C# objects.

public class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Range(0.01, 1000.00)]
    public decimal Price { get; set; }
}

public class ProductController : Controller
{
    [HttpPost]
    public IActionResult Create(Product product)
    {
        if (ModelState.IsValid)
        {
            // Save the product
            return RedirectToAction("Index");
        }
        return View(product);
    }
}

Entity Framework Core

Entity Framework Core is an object-relational mapper (ORM) that simplifies data access.

DbContext

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products { get; set; }
}

Migrations

dotnet ef migrations add InitialCreate
dotnet ef database update

LINQ Queries

public IActionResult Index()
{
    var products = _context.Products
                           .Where(p => p.Price > 10)
                           .OrderBy(p => p.Name)
                           .ToList();
    return View(products);
}

Dependency Injection

ASP.NET Core has built-in support for dependency injection.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    services.AddScoped<IProductRepository, ProductRepository>();
    services.AddTransient<INotificationService, EmailNotificationService>();
    services.AddSingleton<IApplicationCache, MemoryCache>();
}

public class ProductController : Controller
{
    private readonly IProductRepository _repository;
    
    public ProductController(IProductRepository repository)
    {
        _repository = repository;
    }
    
    // Controller actions
}

Middleware

Middleware is software that's assembled into an app pipeline to handle requests and responses.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Home/Error");
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Authentication and Authorization

ASP.NET Core provides built-in support for authentication and authorization.

Authentication

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Account/Login";
        });
}

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
    app.UseAuthorization();
}

Authorization

[Authorize]
public class AdminController : Controller
{
    [Authorize(Roles = "SuperAdmin")]
    public IActionResult SecretOperation()
    {
        return View();
    }
}

Web API

ASP.NET Core supports creating RESTful services using Web API.

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly IProductRepository _repository;

    public ProductsController(IProductRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        return _repository.GetAll().ToList();
    }

    [HttpGet("{id}")]
    public ActionResult<Product> GetProduct(int id)
    {
        var product = _repository.GetById(id);
        if (product == null)
        {
            return NotFound();
        }
        return product;
    }

    [HttpPost]
    public ActionResult<Product> PostProduct(Product product)
    {
        _repository.Add(product);
        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }
}

Testing

ASP.NET Core supports unit testing and integration testing.

Unit Testing

public class ProductServiceTests
{
    [Fact]
    public void GetProductById_ReturnsProduct_WhenProductExists()
    {
        // Arrange
        var mockRepository = new Mock<IProductRepository>();
        mockRepository.Setup(repo => repo.GetById(1))
            .Returns(new Product { Id = 1, Name = "Test Product" });
        var productService = new ProductService(mockRepository.Object);

        // Act
        var result = productService.GetProductById(1);

        // Assert
        Assert.NotNull(result);
        Assert.Equal(1, result.Id);
        Assert.Equal("Test Product", result.Name);
    }
}

Integration Testing

public class ProductControllerIntegrationTests : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public ProductControllerIntegrationTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task GetProducts_ReturnsSuccessStatusCode()
    {
        // Arrange
        var client = _factory.CreateClient();

        // Act
        var response = await client.GetAsync("/api/products");

        // Assert
        response.EnsureSuccessStatusCode();
    }
}

Deployment

ASP.NET Core applications can be deployed to various platforms.

Publishing

dotnet publish -c Release

Hosting Options

  • IIS on Windows
  • Nginx on Linux
  • Docker containers
  • Azure App Service
  • AWS Elastic Beanstalk

Best Practices

  1. Follow the Single Responsibility Principle
  2. Use dependency injection
  3. Implement logging using ILogger
  4. Use asynchronous programming with async/await
  5. Secure your application (use HTTPS, implement authentication and authorization)
  6. Use configuration files for app settings
  7. Implement proper exception handling
  8. Write unit and integration tests
  9. Use tag helpers in views
  10. Keep controllers thin, move business logic to services

Example of asynchronous programming:

public class ProductController : Controller
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    public async Task<IActionResult> Index()
    {
        var products = await _productService.GetAllProductsAsync();
        return View(products);
    }
}

2024 © All rights reserved - buraxta.com