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
  • Feedback & Rating feedback
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

Using ProblemDetails to return more robust error information

In this recipe, we will enhance our API’s error handling by leveraging ProblemDetails, a standardized way to provide detailed error information as defined in the HTTP specification.

ProblemDetails allows ApiController to transform error status codes into structured and informative error responses. ProblemDetails is part of the HTTP specification and a great way to return additional error information if something goes wrong with an endpoint. We will explore how to create custom ProblemDetails objects and customize them to include meaningful details, such as including a traceId from HttpContext within the ProblemDetails object itself.

Getting ready

This recipe uses a starter project that includes a basic controller with endpoints already set up and configured. This recipe is not a direct continuation of the preceding recipe.

You can clone the starter project from here: https://github.com/PacktPublishing/ASP.NET-9-Web-API-Cookbook/tree/main/start/chapter01/problemDetails.

How to do it…

  1. Open the Program.cs file. On the line right after AddControllers(), let’s register customization options using AddProblemDetails():
    builder.Services.AddProblemDetails(options =>
        options.CustomizeProblemDetails = (context) =>
        {
            var httpContext = context.HttpContext;
            context.ProblemDetails.Extensions["traceId"] = Activity.
                Current?.Id ?? httpContext.TraceIdentifier;
            context.ProblemDetails.Extensions["supportContact"] = 
                "[email protected]";
  2. Starting on the next line, let’s enhance our ProblemDetails by adding custom messages for different status codes:
            if (context.ProblemDetails.Status == StatusCodes.
                Status401Unauthorized)
            {
                context.ProblemDetails.Title = "Unauthorized
                                                Access";
                context.ProblemDetails.Detail = "You are not
                        authorized to access this resource.";
            }
            else if (context.ProblemDetails.Status == StatusCodes.
                     Status404NotFound)
            {
                context.ProblemDetails.Title = "Resource Not Found";
                context.ProblemDetails.Detail = "The resource you
                                  are looking for was not found.";
            }
            else
            {
                context.ProblemDetails.Title = "An unexpected error
                                                occurred";
                context.ProblemDetails.Detail = "An unexpected error
                              occurred. Please try again later.";
            }
        });
  3. Navigate to ProductsController.cs, in the Controllers folder. Modify the endpoint that retrieves a product by its ID endpoint. We are going to specify the various responses we expect from the endpoint using the ProducesResponseType attribute and return appropriate ProblemDetails objects for error responses:
    // GET: /products/{id}
    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductDTO))]
    [ProducesResponseType(StatusCodes.Status404NotFound, Type = typeof(ProblemDetails))]
    [ProducesResponseType(StatusCodes.Status401Unauthorized, Type = typeof(ProblemDetails))]
    [ProducesResponseType(StatusCodes.Status500InternalServerError, Type = typeof(ProblemDetails))]
    public async Task<ActionResult<ProductDTO>> GetAProduct(int id)
    {
        logger.LogInformation($"Retrieving product with id {id}");
  4. Create a try block to attempt to retrieve our product:
    try
        {
            var product = await productsService.GetAProductAsync(
                id);
            if (product == null)
            {
                return Problem(
                    detail: $"Product with ID {id} was not found.",
                    title: "Product not found",
                    statusCode: StatusCodes.Status404NotFound,
                    instance: HttpContext.TraceIdentifier
                    );
                }
                return Ok(product);
            }
  5. Now add a catch for other errors. Let’s catch Unauthorized Access, which will return its own ProblemDetails:
            catch (UnauthorizedAccessException ex)
            {
                logger.LogError(ex, "Unauthorized access");
                return Problem(
                    detail: ex.Message,
                    title: "Unauthorized Access",
                    statusCode: StatusCodes.Status401Unauthorized,
                    instance: HttpContext.TraceIdentifier
                );
            }
  6. Finally, let’s also catch general exceptions:
            catch (Exception ex)
            {
                logger.LogError(ex, $"An error occurred while                 retrieving product with id {id}");
                return Problem(
                    detail: "An unexpected error occurred while                     processing your request.",
                    title: "Internal Server Error",
                    statusCode: StatusCodes.                    Status500InternalServerError,
                    instance: HttpContext.TraceIdentifier
                );
            }
        }
  7. Start your app with the following code:
    dotnet run
  8. Direct your web browser to go to the 404 "Not Found" URL for a ProductId that cannot exist.

    Figure 1.1 illustrates trying to get an invalid ID, directly via the web browser:

Figure 1.1 – ProblemDetails returned with traceId and supportContact

Figure 1.1 – ProblemDetails returned with traceId and supportContact

How it works…

In this recipe, we relied on the built-in ProblemDetails support in ASP.NET Core 9 to create custom problem messages when your endpoints return errors.

ProblemDetails objects are automatically generated for some errors. We simply injected AddProblemDetails with the CustomizeProblemDetails class to create custom messages.

In previous versions of ASP.NET Core, we had to rely on external NuGet packages for the meaningful customization of ProblemDetails. ASP.NET Core 9 allows us to have more advanced control over the ProblemDetails response.

By customizing ProblemDetails, we can provide more detailed and useful error information to the clients, including trace IDs and support contact information.

See also

ProblemDetails is not unique to ASP.NET Core—read all about the ProblemDetails HTTP spec here: https://datatracker.ietf.org/doc/html/rfc9457.

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