ASP.NET Core 9 Web API Cookbook (eBook)
348 Seiten
Packt Publishing (Verlag)
978-1-83588-035-7 (ISBN)
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
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 methodologiesKey FeaturesMaster the lifecycle of ASP.NET Core web APIs by confidently building, testing, monitoring, and securing your applicationsExplore advanced topics like GraphQL, SignalR, and microservices to create feature-rich APIsDiscover cloud deployment strategies to ensure your APIs are ready for modern infrastructurePurchase of the print or Kindle book includes a free PDF eBookBook DescriptionDiscover 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 learnImplement HybridCache with stampede protection to replace distributed and in-memory cachesPerform unit, integration, and contract testing to ensure robustness and reliabilityOptimize API performance using output and response caching with tag-based invalidationDesign custom middleware for rate limiting, centralized exception handling, health checks, and moreStreamline API troubleshooting using Serilog's structured logging and Seq's powerful log visualization for quick insightsSecure your APIs with authentication, authorization, and HTTPS enforcementWho this book is forThis 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]]>
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... |
| Erscheint lt. Verlag | 24.4.2025 |
|---|---|
| Sprache | englisch |
| Themenwelt | Mathematik / Informatik ► Informatik |
| ISBN-10 | 1-83588-035-5 / 1835880355 |
| ISBN-13 | 978-1-83588-035-7 / 9781835880357 |
| Informationen gemäß Produktsicherheitsverordnung (GPSR) | |
| Haben Sie eine Frage zum Produkt? |
Digital Rights Management: ohne DRM
Dieses eBook enthält kein DRM oder Kopierschutz. Eine Weitergabe an Dritte ist jedoch rechtlich nicht zulässig, weil Sie beim Kauf nur die Rechte an der persönlichen Nutzung erwerben.
Dateiformat: EPUB (Electronic Publication)
EPUB ist ein offener Standard für eBooks und eignet sich besonders zur Darstellung von Belletristik und Sachbüchern. Der Fließtext wird dynamisch an die Display- und Schriftgröße angepasst. Auch für mobile Lesegeräte ist EPUB daher gut geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür die kostenlose Software Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür eine kostenlose App.
Geräteliste und zusätzliche Hinweise
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich