Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
ASP.NET Core 9 Web API Cookbook

You're reading from   ASP.NET Core 9 Web API Cookbook Over 60 hands-on recipes for building and securing enterprise web APIs with REST, GraphQL, and more

Arrow left icon
Product type Paperback
Published in Apr 2025
Publisher Packt
ISBN-13 9781835880340
Length 348 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Luke Avedon Luke Avedon
Author Profile Icon Luke Avedon
Luke Avedon
Garry Cabrera Garry Cabrera
Author Profile Icon Garry Cabrera
Garry Cabrera
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Practical Data Access in ASP.NET Core Web APIs 2. Chapter 2: Mastering Resource Creation and Validation FREE CHAPTER 3. Chapter 3: Securing Your Web API 4. Chapter 4: Creating Custom Middleware 5. Chapter 5: Creating Comprehensive Logging Solutions 6. Chapter 6: Real-Time Communication with SignalR 7. Chapter 7: Building Robust API Tests: a Guide to Unit and Integration Testing 8. Chapter 8: GraphQL: Designing Flexible and Efficient APIs 9. Chapter 9: Deploying and Managing Your WebAPI in the Cloud 10. Chapter 10: The Craft of Caching 11. Chapter 11: Beyond the Core 12. Chapter 12: Unlock Your Exclusive Benefits 13. Index 14. Other Books You May Enjoy

Configuring a CORS policy to expose pagination metadata

In this recipe, we will allow clients to access pagination metadata from the server response by configuring a special CORS policy that exposes pagination metadata.

Getting ready

This recipe picks up exactly where the preceding recipe ended. If you are jumping around in the book, you can begin this recipe following along at https://github.com/PacktPublishing/ASP.NET-9-Web-API-Cookbook/tree/main/start/chapter01/CORS.

How to do it…

  1. Register a new CORS policy that allows clients to consume your X-Pagination data.
  2. Navigate to the Program.cs file and place the following code right after where you register your ProductService but before var app = builder.Build();:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder =>
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .WithExposedHeaders("X-Pagination"));
    });
  3. Right before app.MapControllers(), enable the CORS policy, like so:
    app.UseCors("CorsPolicy");
    app.MapControllers();
    app.Run();
  4. Run your API with the new CORS policy:
    dotnet run
  5. One way to confirm that CORS is allowing our response headers to be displayed is simply via the Network tab in our browser:
Figure 1.4: Note HasPreviousPage and HasNextPage in the X-Pagination header

Figure 1.4: Note HasPreviousPage and HasNextPage in the X-Pagination header

Important note

Keep in mind that, when testing on localhost, a CORS policy is more lenient and you will probably see these headers regardless. You might not see the full impact of CORS during local development. This recipe is critical when deploying your web API and allowing a variety of clients to consume your API.

How it works…

We applied a CORS policy that allows requests from any origin, AllowAnyOrigin. When the client consuming our API is hosted on a different origin than the API, we have to start thinking about CORS policies. We added the WithExposedHeaders("X-Pagination") policy to ensure that the header that contains our pagination data is accessible to the client.

lock icon The rest of the chapter is locked
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
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon