ASP.NET Core 9 Web API Cookbook - Luke Avedon - E-Book

ASP.NET Core 9 Web API Cookbook E-Book

Luke Avedon

0,0
28,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Embrace the future of web API development with ASP.NET Core 9—from REST best practices to real-time SignalR, and from HybridCache to .NET Aspire deployment—through hands-on recipes and proven methodologies

Key Features

  • Master the lifecycle of ASP.NET Core web APIs by confidently building, testing, monitoring, and securing your applications
  • Explore advanced topics like GraphQL, SignalR, and microservices to create feature-rich APIs
  • Discover cloud deployment strategies to ensure your APIs are ready for modern infrastructure
  • Purchase of the print or Kindle book includes a free PDF eBook

Book Description

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.

What you will learn

  • Implement HybridCache with stampede protection to replace distributed and in-memory caches
  • Perform unit, integration, and contract testing to ensure robustness and reliability
  • Optimize API performance using output and response caching with tag-based invalidation
  • Design custom middleware for rate limiting, centralized exception handling, health checks, and more
  • Streamline API troubleshooting using Serilog's structured logging and Seq's powerful log visualization for quick insights
  • Secure your APIs with authentication, authorization, and HTTPS enforcement

Who this book is for

This book is for intermediate to advanced developers—whether you're a .NET, backend, full-stack, or DevOps professional—looking to build and secure APIs with ASP.NET Core. It’s also ideal for those experienced in Java or Go who want to transition to ASP.NET Core, or developers familiar with C# and .NET aiming to deepen their API skills. A working knowledge of web APIs and the .NET ecosystem is assumed, so you can jump straight into practical recipes

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 311

Veröffentlichungsjahr: 2025

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



ASP.NET 9 Core Web API Cookbook

Recipes for building and securing modern web APIs with the power of REST, GraphQL, and more

Luke Avedon

Garry Cabrera

ASP.NET 9 Core Web API Cookbook

Copyright © 2025 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Portfolio Director: Ashwin Nair

Relationship Lead: Suman Sen

Program Manager: Aparna Nair

Content Engineer: Runcil Rebello

Technical Editor: Sweety Pagaria

Copy Editor: Safis Editing

Proofreader: Runcil Rebello

Indexer: Tejal Soni

Production Designer: Prashant Ghare

Growth Lead: Priyadarshini Sharma

First published: April 2025

Production reference: 1280325

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-83588-034-0

www.packtpub.com

To my amazing wife, Megan, who sacrificed an enormous – ridiculous – amount to make this book possible. To my son James.

– Luke Avedon

To my wonderful and amazing wife, Angelica. To my daughter, Amalia, who’s my princess and future astronaut.

– Garry Cabrera

Contributors

About the authors

Luke Avedon has been contributing to the software development lifecycle for nearly a decade. In recent years, he has focused exclusively on .NET development. He helped to design and implement an ASP.NET Core API for a leading healthcare company, serving as the backbone for a system supporting nearly one billion USD in revenue. Luke has also developed secure solutions for integrating vendor APIs and upgrading legacy .NET APIs to help comply with Department of Defense GCC high-security standards. Additionally, he contributed to the development of large-scale AI models for a major technology company, gaining valuable insights into the intersection of AI and software engineering.

 

Garry Cabrera has seven years of expertise in building robust backend APIs for major financial institutions, including Credit Suisse and Bank of America. Though he specializes in .NET and Java development, Garry’s technical versatility extends to Python and Groovy, enabling him to adapt solutions to diverse requirements. His deep knowledge of relational databases—SQL Server, MySQL, and Oracle—combined with proficiency in ORMs such as Hibernate, allows him to create efficient and scalable data access layers. Garry’s integration expertise with Apache Camel and SSIS has proven invaluable in establishing seamless data flows across complex enterprise systems.

About the reviewer

Gulab Chand Tejwani is a seasoned professional in digital marketing, data analysis, and full-stack web development. Founder of Technet Consultancy in 2011, he specializes in project management and innovative tech solutions. With over 20 years of experience in Microsoft technologies, he holds certifications such as PMP, MCT, and MCPS. Tejwani has also contributed as a director at Learnotics LLP and TechnoSmart Academy, mentoring emerging talents. He holds an MCA from IGNOU and an MBA in IT from Sikkim Manipal University. Fluent in various tech domains, he continues to inspire through his expertise.

Table of Contents

Preface

1

Practical Data Access in ASP.NET Core Web APIs

Technical requirements

Creating a mock database for EF Core with Bogus

Getting ready

How to do it…

How it works…

See also...

Using ProblemDetails to return more robust error information

Getting ready

How to do it…

How it works…

See also

Creating a categories endpoint using the new LINQ CountBy() method

Getting ready

How to do it…

How it works…

Implementing KeySet pagination

Getting ready

How to do it…

How it works…

See also

Configuring a CORS policy to expose pagination metadata

Getting ready

How to do it…

How it works…

Implementing efficient first- and last-page access with EF Core

Getting ready

How to do it…

How it works…

See also

Testing the API in PowerShell

Getting ready

How to do it…

How it works…

Using the new AggregateBy LINQ method to return the average price per category

Getting ready

How to do it…

How it works…

See also

2

Mastering Resource Creation and Validation

Technical requirements

Model validation with data annotations

Getting ready

How to do it…

How it works…

Creating a custom validation attribute

Getting ready

How to do it…

How it works…

Implementing complex validation logic with IValidateObject

Getting ready

How to do It…

How it works…

Creating complex validation rules with FluentValidation

Getting ready

How to do it…

How it works…

See also

Updating resources with PUT and AutoMapper

Getting ready

How to do it…

How it works…

Managing cascade delete with AutoMapper

Getting ready

How to do it…

How it works…

Updating specific model fields with PATCH and JsonPatchDocument

Getting ready

How to do it…

How it works…

See also

3

Securing Your Web API

Technical requirements

Rejecting HTTP requests with custom ProblemDetails middleware

Getting ready

How to do it…

How it works…

Setting up HTTPS on a custom domain – creating a self-signed certificate with PowerShell

Getting ready

How to do it…

How it works...

See also…

Setting up ASP.NET Core Identity

Getting ready…

How to do it…

How it works…

Using cookie authentication in ASP.NET Core Web API

Getting ready…

How to do it…

How it works…

JWT authentication with Identity

Getting ready…

How to do it…

How it works…

Implementing policy-based and role-based authentication

Getting ready…

How to do it…

How it works…

See also...

4

Creating Custom Middleware

Technical requirements

Building a health report for your API

Getting ready

How to do it…

How it works…

Adding health checks to OpenAPI using the new document transformers

Getting ready

How to do it…

How it works…

See also…

Creating a custom database performance health check

Getting ready

How to do it…

How it works…

Creating custom middleware for adding security headers

Getting ready

How to do it…

How it works…

Creating factory middleware for centralized data transformation

Getting ready

How to do it…

How it works…

5

Creating Comprehensive Logging Solutions

Technical requirements

Logging all requests with Serilog and Seq

Getting ready

How to do it…

How it works…

Improving request logs with custom DiagnosticContext properties

Getting ready

How to do it…

How it works…

Logging controller and action method names

Getting ready

How to do it…

How it works…

See also

Unified request logging – combining ASP.NET Core’s HttpLogging with Serilog and Seq

Getting ready

How to do it...

How it works…

Crafting Serilog log objects in ASP.NET Core controllers

Getting ready

How to do it…

How it works…

See also

Configuring Seq and Serilog with an API Key

Getting ready

How to do it…

How it works…

See also

6

Real-Time Communication with SignalR

Technical requirements

Creating a real-time opinion poll in SignalR

Getting ready

How to do it…

How it works…

JWT authentication flow – identity from controller login to SignalR connection

Getting ready

How to do it…

How it works…

Invoking a hub method from an HTTP controller – announcing user login

Getting ready

How to do it…

How it works…

User customization with IUserIdProvider

Getting ready

How to do it…

How it works…

Sending direct messages via SignalR

Getting ready

How to do it…

How it works…

Implementing admin-controlled group management in SignalR

Getting ready

How to do it…

How it works…

7

Building Robust API Tests: a Guide to Unit and Integration Testing

Technical requirements

Unit testing an API service method with xUnit

Getting ready

How to do it…

How it works…

Unit testing with AutoFixture, NSubstitute, and FluentAssertions

Getting ready

How to do it…

How it works…

See also…

Organizing unit tests with a base service class

Getting ready

How to do it…

How it works…

Testing pagination with custom UrlHelper and NSubstitute

Getting ready

How to do it…

How it works…

Controller unit tests with custom fixtures

Getting ready

How to do it…

How it works…

Web API integration testing

Getting ready

How to do it…

How it works…

Authentication in integration testing

Getting ready

How to do it…

How it works…

See also…

8

GraphQL: Designing Flexible and Efficient APIs

Technical requirements

Real-time updates via GraphQL subscriptions

Getting ready

How to do it…

How it works…

Mutations for modifying data in GraphQL

Getting ready

How to do it…

How it works…

Implementing efficient pagination in GraphQL

Getting ready

How to do it…

How it works…

Filtering and sorting with GraphQL

Getting ready

How to do it…

How it works…

Distributed GraphQL with Hot Chocolate Fusion

Getting ready

How to do it…

How it works…

9

Deploying and Managing Your WebAPI in the Cloud

Technical requirements

Building with Azure – core service integration through geolocation

Getting ready…

How to do it…

How it works…

Azure Key Vault – securing configuration with custom health checks

Getting ready…

How to do it…

How it works…

Creating an API gateway with a YARP reverse proxy and a custom load-balancing policy

Getting ready…

How to do it…

How it works…

Migrating a distributed API to .NET Aspire for unified orchestration and monitoring

Getting ready…

How to do it…

How it works…

Integrating dockerized services with .NET Aspire – an example with Prometheus

Getting ready…

How to do it…

How it works…

10

The Craft of Caching

Technical requirements

Manual client-side response caching with HTTP headers

Getting ready

How to do it…

How it works…

Validating client-side cache with Last-Modified headers

Getting ready

How to do it…

How it works…

There’s more…

Client-side ETag cache validation with the ResponseCache attribute

Getting ready

How to do it…

How it works…

See also

Output caching with Aspire Redis

Getting ready

How to do it…

How it works…

Server-side caching with IDistributedCache and Redis via .NET Aspire

Getting ready

How to do it...

How it works...

Using the new HybridCache library to simplify distributed caching

Getting ready

How to do it….

How it works…

See also

11

Beyond the Core

Technical requirements

Microservice communication via gRPC and .NET Aspire

Getting ready

How to do it…

How it works…

Implementing bidirectional streaming with gRPC in .NET Aspire

Getting ready

How to do it…

How it works…

Implementing real-time updates with Dapr pub/sub in .NET Aspire

Getting ready

How to do it…

How it works…

Sharing state between services with Dapr state stores

Getting ready

How to do it…

How it works…

Index

Other Books You May Enjoy

Preface

Since ASP.NET was completely redesigned and rebranded as the open source ASP.NET Core in 2016, ASP.NET Core has gone on to establish itself as the leading framework for building backend Web APIs. The framework consistently outranks other enterprise solutions in performance benchmarks while offering a robust feature set that includes built-in dependency injection, a lightweight modular HTTP request pipeline, and powerful model binding that automatically maps data from HTTP requests to action method parameters.

With the wealth of information available on ASP.NET Core, finding practical, implementation-focused guidance can be challenging. This cookbook cuts through the theory to provide you with clear, actionable recipes for solving common Web API development challenges.

We have endeavored to make every recipe practical and immediately useful for solving real problems we encounter on the job. The recipes in this cookbook cover authentication, performance optimization, data access, caching strategies, real-time communication, and cloud integration. Whether you’re building a simple REST API or architecting complex distributed systems, you’ll find relevant, practical solutions you can immediately apply to your projects.

Who this book is for

This book is for intermediate-level .NET developers looking for actionable solutions to common problems in Web API development. Those coming from another backend stack such as Java will find this book a quick crash course in building web APIs with .NET. The book assumes working knowledge of C# and ASP.NET Core fundamentals, focusing instead on practical solutions for performance optimization, security implementation, caching strategies, real-time communication, and distributed system architecture. You’ll learn industry best practices and real-world techniques that can be immediately applied to your projects, whether you’re designing new APIs or enhancing existing ones.

What this book covers

Chapter 1, Practical Data Access in ASP.NET Core Web APIs, focuses on efficient data retrieval with KeySet pagination using Entity Framework Core. This chapter covers creating mock databases with Bogus, enhancing error handling via ProblemDetails, and exploring a couple of the new LINQ methods for data aggregation. It also includes configuring CORS for metadata exposure and optimizing access to the first and last pages.

Chapter 2, Mastering Resource Creation and Validation, explores creating, validating, and updating resources in your web API. We cover model validation techniques using data annotations, custom validation attributes, and the FluentValidation library. We implement PUT and PATCH requests for updating resources, leveraging AutoMapper for efficient object mapping, and managing cascade deletes. Additionally, this chapter introduces Scalar as a user-friendly alternative to Swagger UI for interactive Open API documentation.

Chapter 3, Securing Your Web API, covers essential security strategies for ASP.NET Core APIs. The chapter focuses on enforcing HTTPS through custom middleware and certificates for various environments. It demonstrates implementing ASP.NET Core Identity, cookie-based authentication (still relevant for interfacing with legacy systems and browser-based clients), and JWT-based authentication for stateless authorization. Policy-based and role-based authorization are explored to create robust security boundaries to protect your API.

Chapter 4, Creating Custom Middleware, explains how to extend ASP.NET Core’s request pipeline with specialized components that enhance your API. The chapter demonstrates implementing health checks to monitor API status, including a custom database performance health check that measures query execution times against configurable thresholds. It shows how to document these health endpoints in OpenAPI using the new Document Transformers feature. Additionally, we will create security-enhancing middleware for adding protective headers and factory-based middleware for on-the-fly response format transformations.

Chapter 5, Creating Comprehensive Logging Solutions, demonstrates how to capture and analyze API activity using Serilog and Seq, creating a centralized logging system that enhances debugging and monitoring. It covers logging all HTTP requests with custom diagnostic context properties, tracking controller and action method names, combining ASP.NET Core’s HttpLogging with Serilog, crafting detailed structured log objects in controllers, and configuring secure access to logging services with API keys.

Chapter 6, Real-Time Communication with SignalR, demonstrates how to implement bidirectional, real-time functionality in your Web API applications. The chapter shows how to create interactive experiences such as live polls, real-time chat, and private messaging using Microsoft’s SignalR technology. We cover integrating JWT authentication with SignalR connections, invoking hub methods from HTTP controllers, customizing user identification, implementing direct messaging between specific users, and creating admin-controlled group management.

Chapter 7, Building Robust API Tests: a Guide to Unit and Integration Testing, is all about unit and integration testing. We will set up xUnit unit tests and enhance them with AutoFixture, NSubstitute, and FluentAssertions. For integration testing, we use WebApplicationFactory with authentication to test the complete API pipeline.

Chapter 8, GraphQL: Designing Flexible and Efficient APIs, provides practical recipes for implementing GraphQL APIs, a powerful alternative to REST. We cover creating real-time updates with GraphQL subscriptions, implementing mutations for data modifications, and building efficient pagination, filtering, and sorting capabilities that work with IQueryable. Also, we use Hot Chocolate Fusion to combine multiple independent GraphQL APIs into a unified schema through a gateway pattern, a modern approach to distributed GraphQL valuable in microservice architectures.

Chapter 9, Deploying and Managing Your WebAPI in the Cloud, guides you through cloud deployment and management of ASP.NET Core web APIs. We cover integrating Azure core services, securing configurations with Key Vault, and crafting API gateways with YARP for efficient traffic management and geo-based load balancing. Additionally, we explore migrating to .NET Aspire for unified orchestration, monitoring, and integrating Dockerized services such as Prometheus for persistent telemetry data.

Chapter 10, The Craft of Caching, provides various caching strategies for ASP.NET Core web APIs, progressing from client-side to server-side solutions. It begins with manual HTTP header manipulation and the ResponseCache attribute for client-side caching. The chapter then transitions to server-side distributed caching using Redis via .NET Aspire, covering output caching, IDistributedCache, and the new HybridCache. HybridCache is highlighted as a powerful tool that combines in-memory and distributed caching for optimal performance and simplified cache management.

Chapter 11, Beyond the Core, is about inter-service communication patterns in distributed .NET applications. This chapter provides recipes for microservice communication through gRPC in .NET Aspire, implementing both unary calls and bidirectional streaming for real-time data exchange. Next, we use Distributed Application Runtime (Dapr) with .NET Aspire to implement service-to-service interactions, covering publish/subscribe messaging for real-time updates and state management for sharing data between services.

To get the most out of this book

The recipes in this book are built with .NET 9, which was released in November 2024 as a standard-term support (STS) release with 18 months of support from Microsoft. .NET follows a predictable release cycle with a new version every year – even-numbered versions (such as .NET 8) are long-term support (LTS) releases with 3 years of support, while odd-numbered versions (such as .NET 9) are STS releases. All code examples have been tested with .NET 9, but the patterns and approaches should remain applicable to future versions as well. Visit https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core for more information.

Software/Hardware covered in the book

OS Requirements

.NET 9 SDK

Windows, Mac OS X, and Linux (Any)

PowerShell 7.5

Docker Desktop

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

For Windows users, we recommend Windows Terminal for the PowerShell examples.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/ASP.NET-9-Web-API-Cookbook. In case there’s an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Replace throw new NotImplementedException(); with our registration name and a dictionary to store the results of testing our database.”

A block of code is set as follows:

using System.Data; using System.Diagnostics; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options;

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

using System.Data; using System.Diagnostics; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options;

Any command-line input or output is written as follows:

dotnet add package Grpc.Net.ClientFactorydotnet add package Grpc.Toolsdotnet add package Google.Protobuf

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “One way to confirm that CORS is allowing our response headers to be displayed is simply via the Network tab in our browser.”

Tips or important notes

Appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There’s more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There’s more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read ASP.NET 9 Core Web API Cookbook, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/978-1-83588-034-0

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly