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

Creating a categories endpoint using the new LINQ CountBy() method

.NET 9 introduces CountBy(), a powerful new LINQ method that simplifies the common task of grouping and counting elements. This method replaces the traditional pattern of combining GroupBy with Count, making your code more concise and readable. In this recipe, we’ll create an endpoint that uses CountBy() to efficiently report how many products exist in each category, demonstrating how this new method can simplify data aggregation tasks.

Getting ready

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

How to do it…

  1. In the starter project, let’s navigate to the Models folder and create a new file called CategoryDTO.cs. In this file, we will define a new DTO record:
    namespace CountBy.Models;
    public record CategoryDTO
    {
        public int CategoryId { get; init; }
        public int ProductCount { get; init; }
    }
  2. In the Services folder, create a file named IProductsService.cs. In this file, we are going to define a contract for a GetCategoryInfoAsync service method:
    using CountBy.Models;
    namespace CountBy.Services;
    public interface IProductsService {
        Task<IEnumerable<ProductDTO>> GetAllProductsAsync();
        Task<IReadOnlyCollection<CategoryDTO>>         GetCategoryInfoAsync();
    }
  3. Implement the service method using CountBy() on your DbContext:
    public async Task<IReadOnlyCollection<CategoryDTO>> GetCategoryInfoAsync()
        {
            var products = await  context.Products.AsNoTracking().                       ToListAsync();
            var productsByCategory = products.CountBy(p =>             p.CategoryId).OrderBy(x => x.Key);
            return productsByCategory.Select(categoryGroup => new
            CategoryDTO
            {
                CategoryId = categoryGroup.Key,
                ProductCount = categoryGroup.Value
            }).ToList(
        }
  4. Now let’s navigate to our ProductsController.cs file in the Controllers folder. Add the attributes to the CategoryInfo endpoint:
    // GET: /Products/CategoryInfo
    [HttpGet("CategoryInfo")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CategoryDTO>))]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
  5. Let’s expand the GetCategoryInfo controller method:
    public async Task<ActionResult<IEnumerable<CategoryDTO>>> GetCategoryInfo()
    {
        logger.LogInformation("Retrieving Category Info");
        try
        {
            var products = await productsService.            GetCategoryInfoAsync();
            if (!products.Any())
                return NoContent();
            return Ok(products);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred while                   retrieving all products");
            return StatusCode(StatusCodes.                      Status500InternalServerError);
            }
        }
  6. Build your new project:
    dotnet run
  7. Test out your new endpoint at Products/CategoryInfo and see how many products you have in each category.

    Since this is a GET endpoint, we can test it with our web browser, as shown in the following screenshot:

Figure 1.2 – Our data now with a categoryId

Figure 1.2 – Our data now with a categoryId

How it works…

We explored the use of the new LINQ CountBy() operator to create an endpoint that returns how many products you have by each category. CountBy() provides a new, more elegant way to categorize data, replacing the need to use both GroupBy() and Count() in aggregation operations. It’s important to note that CountBy() is a LINQ-to-objects method, not a LINQ-to-entities method. This means when used with EF Core, it will first materialize the query (loading all records into memory) before performing the counting operation. For large datasets in production scenarios, you might want to consider using GroupBy() directly on the IQueryable instead. In addition to database queries, CountBy() is particularly useful for in-memory operations such as analyzing API usage statistics by grouping and counting requests based on different criteria such as client IP, user agent, or endpoint path.

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