Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying ASP.NET Core 9 Web API Cookbook
  • Table Of Contents Toc
ASP.NET Core 9 Web API Cookbook

ASP.NET Core 9 Web API Cookbook

By : Luke Avedon, Garry Cabrera
5 (1)
close
close
ASP.NET Core 9 Web API Cookbook

ASP.NET Core 9 Web API Cookbook

5 (1)
By: Luke Avedon, Garry Cabrera

Overview of this book

Discover what makes ASP.NET Core 9 a powerful and versatile framework for building modern web APIs that are both scalable and secure. This comprehensive, recipe-based guide leverages the authors’ decade-long experience in software development to equip developers with the knowledge to create robust web API solutions using the framework's most powerful features. Designed for intermediate to advanced .NET developers, this cookbook contains hands-on recipes that demonstrate how to efficiently build, optimize, and secure APIs using this cutting-edge technology. You'll master essential topics, such as creating RESTful APIs, implementing advanced data access strategies, securing your APIs, creating custom middleware, and enhancing your logging capabilities. The book goes beyond traditional API development by introducing GraphQL, SignalR, and gRPC, offering insights into how these technologies can extend the reach of your APIs. To prepare you for real-world challenges, the recipes cover testing methodologies, cloud deployment, legacy system integration, and advanced concepts like microservices and Hangfire. By the end of this book, you’ll gain the expertise needed to build and manage enterprise-grade web APIs with ASP.NET Core 9. *Email sign-up and proof of purchase required
Table of Contents (14 chapters)
close
close

Creating a mock database for EF Core with Bogus

Let’s start by creating a basic web API that will serve as the foundation for the rest of the projects in this chapter. We will use SQLite’s in-memory database provider with EF Core, eliminating the need for database files or server connections. The API’s database will be populated with mock data generated by Bogus.

Getting ready

To begin, you will need the following:

How to do it…

  1. Open the terminal and create a new web API:
    dotnet new webapi -o mockAPI -f net9.0 --no-https --auth none
  2. Navigate to the project directory and create a new .gitignore file:
    dotnet new gitignore
  3. Install EF Core and its SQLite provider:
    dotnet add package Microsoft.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.Sqlite
  4. Install Bogus for creating mock data. New in .NET 9, we also have to manually add Swagger support:
    dotnet add package Bogus
    dotnet add package Swashbuckle.AspNetCore.SwaggerUI
  5. Create a folder named Models. Create a file called Product.cs and fill in the following Product class:
    namespace mockAPI.Models;
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public int CategoryId { get; set; }
    }
  6. Create a sibling folder called Data. In that folder, create your AppDbContext.cs file. Fill in a AppDbContext class, which will inherit from DbContext:
    using Microsoft.EntityFrameworkCore;
    using mockAPI.Models;
    namespace mockAPI.Data;
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):
            base(options) { }
  7. Still inside the AppDbContext class, on the next line, define the 'DbSet' property to use your new Products class:
    public DbSet<Product> Products { get; set; }
  8. On the next line, define the OnModelCreating method:
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
         modelBuilder.Entity<Product>(entity =>
         {
             entity.HasKey(e => e.Id);
             entity.Property(e => e.Name).IsRequired();
             entity.Property(e => e.Price).HasColumnType(
                 "decimal(18,2)");
         });
    }
  9. Open the Program.cs file. Delete all the boilerplate code that .NET generated; we are going to start from scratch.
  10. At the top of Program.cs, import our new Data namespace, as well as the namespace for models and Bogus itself:
    using mockAPI.Data;
    using mockAPI.Models;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Data.Sqlite;
    using Bogus;
  11. Next, we will create the builder, register the OpenAPI service, and create a connection to our in-memory database that will persist for the application’s lifetime:
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddOpenApi();
    var connection = new SqliteConnection("DataSource=:memory:");
    connection.Open();
  12. After creating the SQLite connection, we need to add the DbContext registration:
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlite(connection));
  13. On the next line, inject a scoped service that opens a connection to the in-memory database and then confirms that the connection has been created:
    var app = builder.Build();
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var context = services.GetRequiredService<AppDbContext>();
        context.Database.EnsureCreated();
    }

Service lifetime selection

We need to register a scoped service to interact with EF Core’s DbContext. This is counterintuitive; it might seem like a singleton service would be a more appropriate lifetime for working with a database. However, EF Core's DbContext is designed to be short-lived and is not thread-safe for concurrent operations.

  1. Expand the scoped service to seed your in-memory database with fake data, only if your database context is empty:
        if (!context.Products.Any())
        {
            var productFaker = new Faker<Product>()
                .RuleFor(p => p.Name, f => f.Commerce.ProductName())
                .RuleFor(p => p.Price, f => f.Finance.Amount(
                     50,2000))
                .RuleFor(p => p.CategoryId, f => f.Random.Int(
                     1,5));
            var products = productFaker.Generate(10000);
            context.Products.AddRange(products);
            context.SaveChanges();
        }
    }
  2. Let’s add a minimal API endpoint we can use for testing:
    app.MapGet("/products", async (AppDbContext db) => 
        await db.Products.OrderBy(p =>
            p.Id).Take(10).ToListAsync());
  3. Before we run the application, let’s manually add SwaggerUI support:
    app.MapOpenApi();
    if (app.Environment.IsDevelopment())
    {
        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint("/openapi/v1.json", "v1");
        });
    }
    app.Run();
  4. Run the application. You can visit http://localhost<yourport>/swagger/index.html and click on the Products endpoint to see our fake data generated by Bogus:
    dotnet run

How it works…

You registered your AppDbContext with the service provider at startup, which is the standard way to integrate EF Core into ASP.NET Core dependency injection. This allows the database context to be available for your controllers, services, and so on.

You also added a scoped service provider that checks whether your database is empty. The scoped lifetime ensures that a new AppDbContext is created for each request, preventing any data inconsistencies that can plague singleton instances of database connections. If the database is empty, it will be seeded using the Faker<T> class from Bogus.

We also used the SQLite in-memory database provider for EF Core. This allows us to create a database entirely in memory without requiring an external SQLite file. While EF Core also includes an InMemory database provider, it is considered a legacy option and is not recommended for testing. Unlike the InMemory provider, SQLite’s in-memory database supports transactions and raw SQL, making it a closer approximation of a real-world database.

See also...

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
ASP.NET Core 9 Web API Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon