🚀

Tutorial on Creating a .NET Core Web API with C#

Jul 8, 2024

Tutorial on Creating a .NET Core Web API with C# 🚀

Introduction

  • Presenter: Hula Cal
  • Objective: Build a web application using ASP.NET Core and C#
  • Application: Create a game catalog backend for a video game store.
  • Tools: .NET SDK, Visual Studio Code, and necessary extensions.
  • Prerequisites: Basic knowledge of C#, Java, or similar, essentials of web development, and relational databases.

Development Environment Setup

  1. Install .NET SDK
  2. Install Visual Studio Code
  3. VS Code Extensions: C# Dev Kit, REST Client, SQLite.
  4. Verify .NET SDK Installation dotnet --version dotnet --info

Creating a New Project

  • Command-Line: dotnet new webapi -o GameStoreApi
  • VS Code Command Palette -> New Project

ASP.NET Core Application Structure

  • Program.cs: Entry point, setup web application host, middleware, and routes.
  • DbContext: Represents session with the database, queries, and saves instances of entities.
  • Configuration: Store settings in appsettings.json. { "ConnectionStrings": { "GameStore": "Data Source=GameStore.db" } }

Implementing REST API Endpoints

Concepts and Endpoints

  1. GET /games: Retrieve all games
  2. GET /games/{id}: Retrieve game by id
  3. POST /games: Create new game
  4. PUT /games/{id}: Update game by id
  5. DELETE /games/{id}: Delete game by id

Using Dependency Injection (DI)

  • Registering services (GameStoreContext) builder.Services.AddDbContext<GameStoreContext>(options => options.UseSqlite(Configuration.GetConnectionString("GameStore")));
  • Service Lifetimes: Transient, Scoped, Singleton

Data Transfer Objects (DTOs)

  • CreateGameDto, UpdateGameDto, GameDto: Used to transfer data.
  • Entity Framework Core (EF Core): ORM to manage data between C# objects and relational database.
  • Migrations: Add and apply migrations to create and update database schema. dotnet ef migrations add InitialCreate dotnet ef database update

Ensuring Valid Inputs

  • Data Annotations: Define validation rules. Used Required and StringLength annotations.
  • Endpoint Filters: Automatically validate DTOs.

Implement REST API Methods

  • GET Games app.MapGet("/games", async (GameStoreContext db) => await db.Games.ToListAsync());
  • GET Game by ID app.MapGet("/games/{id}", async (GameStoreContext db, int id) => await db.Games.FindAsync(id));
  • POST Game app.MapPost("/games", async (GameStoreContext db, CreateGameDto newGame) => {...};
  • PUT Game app.MapPut("/games/{id}", async (GameStoreContext db, int id, UpdateGameDto updatedGame) => {...};
  • DELETE Game app.MapDelete("/games/{id}", async (GameStoreContext db, int id) => {...}

Implementing Async Programming

  • Use async and await for database operations.
  • Example: app.MapGet("/games", async (GameStoreContext db) => await db.Games.AsNoTracking().ToListAsync());

Adding a Genres Endpoint

  1. Create GenreDto public record GenreDto(int Id, string Name);
  2. Map to DTOs
  3. Endpoint Implementation: List all genres. app.MapGet("/genres", async (GameStoreContext db) => await db.Genres.AsNoTracking().ToListAsync());

Configuring Development Environment

  • NuGet Packages: Include necessary EF Core packages.
  • Logging Configurations: Modify logging settings for development.
  • Handling Database Connection Strings: Store in appsettings.json, read using DI configuration.

Integration with a Frontend

  • Frontend Framework: Blazor or similar.
  • Interaction with Backend API: Verify through UI.

Best Practices

  • Keep DTOs and Data Models Separate: Flexibility in changing internal models.
  • Use Extension Methods for Mappings: Cleaner and modular code.
  • Service Lifetimes: Use appropriate lifetime for services (Transient, Scoped, Singleton).
  • Asynchronous Methods: Ensuring efficient handling of requests.

Conclusion

  • Successfully built a complete backend web API using ASP.NET Core and C#.
  • Explored core concepts, practical implementation techniques, and integrated with a frontend.
  • Encouraged further learning and refinement for robust backend services.