28,99 €
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
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:
Seitenzahl: 311
Veröffentlichungsjahr: 2025
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
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
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.
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.
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.
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.
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.
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.
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!
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.ProtobufBold: 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.
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:
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.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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.
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.
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 belowhttps://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