- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Guided: Making ASP.NET Core 10 Web APIs More Resilient
In this lab, you will learn how to build resilient web APIs using ASP.NET. As a developer, uptimes of 99.99% are not only expected but essential if you want to build a consistent user base. For example, imagine doing the hard work of building an e-commerce platform only for it to crash during Black Friday, when purchases are at their highest. Poorly built applications often fail when business activity is at its peak—the worst possible time. In this lab, you’ll learn techniques to help ensure your applications can handle spikes in traffic and remain responsive during critical business operations.
Lab Info
Table of Contents
-
Challenge
Introduction
Hello and welcome to this course on Making ASP.NET Core 10 Web APIs More Resilient. Modern APIs don’t just need to work, they need to fail well. In real-world environments, services are exposed to unpredictable traffic, slow clients, malformed requests, and unexpected failures. A resilient API is designed not only to serve valid requests efficiently, but also to protect itself under stress and communicate clearly when something goes wrong.
In this lab, you will enhance an ASP.NET Core 10 Web API by implementing practical resilience mechanisms that mirror real production safeguards. You’ll move beyond simple endpoint creation and focus on defensive design patterns that make APIs stable, predictable, and robust. This API enables ASP.NET Core’s
ProblemDetailsservice to standardize how errors are returned to clients. Instead of sending custom JSON objects, the API returns structured RFC 7807 Problem Details responses that include a clear error title, description, and HTTP status code. By the end of this lab you will be able to:- Protect Endpoints with Rate Limiting: You will add and configure rate limiting to prevent excessive or abusive traffic from overwhelming your API.
- Enforce Predictable Request Timeouts: Long-running or stalled requests can exhaust server resources and degrade performance for all users. You will configure request timeouts so that delayed operations are cancelled after a defined duration.
- Implement Graceful Error Handling: Instead of exposing raw exceptions or vague responses, your API will return structured and meaningful error messages.
-
Challenge
Protecting Endpoints with Rate Limiting
APIs are designed to be accessible, but unlimited access can quickly become a liability. Without safeguards, a single client can overwhelm your application with repeated requests, either unintentionally through poor design or intentionally through abuse. Even a small spike in traffic can consume CPU, memory, or network resources and degrade performance for legitimate users.
Rate limiting is a defensive mechanism that allows an API to control how frequently clients can access specific endpoints. Instead of allowing unlimited requests, the API enforces a defined threshold and responds with a clear and predictable error when that limit is exceeded.
In this section, you will implement rate limiting in an ASP.NET Core 10 Web API to:
- Restrict the number of requests allowed per client within a defined time window
- Return an appropriate HTTP status code (
429 Too Many Requests) when limits are exceeded - Provide a clear, structured error response explaining why the request was rejected
- Ensure the API remains stable under repeated or abusive traffic
This exercise demonstrates an important principle of resilient system design: protect shared resources before they are exhausted. Rather than allowing performance to degrade silently, the API will enforce boundaries and communicate them clearly. In ASP.NET Core, rate limiting is implemented using the built-in Rate Limiting middleware. Policies are defined in
AddRateLimiter, where you configure how requests are limited and how the API responds when limits are exceeded.You will modify the following key settings to control how the limiter behaves:
- The policy name, which must match the name used by
RequireRateLimitingon the endpoint PermitLimit, which determines how many requests are allowedWindow, which defines the time period in which those requests are counted.
The limiter partitions requests by client IP address, meaning each IP gets its own limit bucket. When the limit is exceeded, the
OnRejectedhandler returns a429 Too Many Requestsresponse with a standardized Problem Details response message. By adjusting these values, you can see how changing the request limit or time window affects how the API accepts or rejects traffic. -
Challenge
Enforce Predictable Request Timeouts
Not every request completes quickly. Some operations may take longer than expected due to slow downstream services, network latency, blocked resources, inefficient code, or even intentional denial of service attacks. If left unchecked, long-running or stalled requests can tie up server threads, consume memory, and degrade overall system performance for other users.
Resilient APIs must enforce clear boundaries on how long a request is allowed to execute. Instead of allowing operations to run indefinitely, the application should cancel requests that exceed a defined time limit and return a predictable, well-structured error response.
In this section, you will configure request timeouts in an ASP.NET Core 10 Web API to ensure that long-running requests are automatically canceled after a defined time limit. In this task, you will explore how to implement request timeouts in an ASP.NET Core Web API to prevent long-running requests from consuming server resources. The
/timeoutendpoint simulates work by delaying the response based on a delay query parameter (for example,/timeout?delay=40). ACancellationTokenSourceis used to enforce a maximum processing time by canceling the request on the server side after a configured number of seconds rather than waiting for the client to disconnect.You will modify the timeout duration in
CancelAfter(...)and add the correct HTTP status code returned when the timeout occurs. When the delay exceeds the configured limit, the API catches the cancellation and returns a standardized Problem Details response error indicating that the session has timed out. By adjusting these values and testing with different delays, you can observe how timeouts help APIs fail predictably instead of allowing stalled requests to run indefinitely. -
Challenge
Implementing Graceful Error Handling Error Code 500
No matter how carefully an API is designed, unexpected errors will occur. Exceptions may be thrown due to invalid assumptions, unhandled edge cases, dependency failures, or unforeseen runtime conditions. In a production environment, these failures must be handled deliberately, not exposed directly to clients.
By default, an unhandled exception can result in vague error messages, stack traces, or inconsistent responses. This not only creates a poor developer experience for API consumers, but can also expose sensitive implementation details.
In this section, you will implement centralized exception handling in an ASP.NET Core 10 Web API. Instead of allowing unhandled exceptions to surface directly, you will intercept them and return a standardized Problem Details response that informs the client that an error occurred without exposing internal system details In this task, you will implement global error handling for unexpected server failures using ASP.NET Core’s
UseExceptionHandlermiddleware. This middleware catches unhandled exceptions that occur anywhere in your application and returns a consistent response to the client instead of exposing internal errors.Inside the handler, you will:
- Set the HTTP status code for a server error.
- Return a standardized Problem Details response using
Results.Problem(). - Modify the missing status code so the API correctly returns a
500 Internal Server Errorwhen an unexpected exception occurs.
Once configured, any unhandled error—such as the optional
/boomdemo route—will trigger this handler, allowing your API to respond safely and predictably when something goes wrong. -
Challenge
Implementing Graceful Error Handling Error Code 405
APIs define clear contracts: specific endpoints support specific HTTP methods. A route designed to retrieve data may allow
GETrequests, while a route intended to create resources may acceptPOSTrequests. When a client sends a request using an unsupported method, the API must respond clearly and predictably.Rather than failing silently or returning a vague error, a resilient API communicates precisely why the request was rejected. The appropriate response in this case is HTTP
405–Method Not Allowed, which indicates that the endpoint exists but does not support the attempted HTTP method.In this section, you will configure your ASP.NET Core 10 Web API to detect unsupported HTTP methods on a valid endpoint and return the correct status code:
405 Method Not Allowed. In this task, you will implement a405 Method Not Allowedresponse to handle cases where a client uses an unsupported HTTP method for an endpoint.The
/inforoute is designed to allowGETrequests, but when aPOSTrequest is sent, the API returns a structured Problem Details response explaining that the method is not permitted. You will add the correct HTTP status code so the API properly indicates that the request method is invalid for this route.By testing the endpoint with different HTTP methods, you can observe how APIs communicate incorrect usage and guide clients toward the correct request type.
-
Challenge
Implementing Graceful Error Handling Error Code 404
In any API, clients may occasionally request endpoints that do not exist. This can happen due to typographical errors, outdated documentation, incorrect URLs, or improper integration. When this occurs, the API must respond clearly and consistently to indicate that the requested resource cannot be found.
The appropriate response in this scenario is HTTP
404–Not Found. This status code communicates that the server is reachable and functioning correctly, but the specific endpoint or resource requested does not exist.In this section, you will configure your ASP.NET Core 10 Web API to detect requests to unknown or undefined routes and return a structured and meaningful
404 Not Foundresponse. In this task, you will implement a404 Not Foundresponse to handle requests for endpoints that do not exist in your API.The application uses a fallback route that catches any request that does not match a defined endpoint and returns a standardized Problem Details response error message. You will add the correct HTTP status code so the API clearly indicates that the requested resource could not be found.
By testing URLs that are not defined in the application, you can observe how APIs respond when clients request routes that do not exist and how consistent error responses improve clarity for API consumers.
-
Challenge
Conclusion
In this lab, you moved beyond building basic endpoints and focused on an equally important aspect of modern API development: resilience.
Resilient APIs are not defined only by how well they handle successful request —they are defined by how predictably and safely they respond under stress, misuse, and failure conditions. Throughout this lab, you implemented foundational techniques that help protect your application and ensure consistent behavior in real-world environments.
You successfully:
- Implemented rate limiting to protect endpoints from excessive or abusive traffic
- Enforced predictable request timeouts to prevent long-running operations from exhausting server resources
- Configured graceful error handling for common scenarios including
404 Not Found,405 Method Not Allowed, and500 Internal Server Error - Validated resilience behavior through scripted testing to confirm the API responds consistently under stress
These mechanisms demonstrate an important principle of professional API design: Failure should be intentional, controlled, and clearly communicated.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.