arsalandywriter.com

Harness the OnionAPI Template for ASP.NET WebAPI in .NET 7

Written on

Introduction

The OnionAPI template is your go-to solution for crafting sophisticated REST APIs. Loaded with useful features and best practices, it can significantly reduce your development time—saving you at least 40 hours compared to starting a REST API project from scratch. This means more time for you to focus on other essential tasks, like enjoying a bowl of Vietnamese Pho noodle soup.

NET 7 officially launched on November 8, 2022, superseding NET 6. With the new OnionAPI v7 Visual Studio template, developers can easily set up REST API projects that adhere to the Clean Architecture pattern, as illustrated in Figure 1.

When you create a new project using the OnionAPI template in Visual Studio, it generates a solution comprising five distinct projects, each prefixed with the project name and featuring its own customizable namespace. Here’s a brief overview of each project’s purpose:

  1. Domain: Contains the entities and common models.
  2. Application: Houses interfaces, CQRS elements, exceptions, and behaviors.
  3. Infrastructure.Persistence: Contains the data access API based on Entity Framework.
  4. Infrastructure.Shared: Includes common services like Mail Service, Date Time Service, and Mock.
  5. WebApi: Contains API controllers that expose REST API resources and endpoints accessible via Swagger.

Content Overview

This tutorial consists of four parts:

Part 1: Download and install the template Learn how to download and install the OnionAPI template for Visual Studio.

Part 2: Scaffold a new Web API project Use the OnionAPI template to create a new ASP.NET CORE Web API project running on .NET v7.

Part 3: Explore the generated source code Examine the source code generated by the template.

Part 4: Test run the Web API project Test the Web API project to ensure everything functions correctly.

Prerequisites

  • Latest .NET Core 7 SDK
  • Visual Studio 2022 Community — a free code editor for C#

Part 1: Download and Install the Template

To download and install a Visual Studio template from the Visual Studio Marketplace, follow these steps:

  1. Launch Visual Studio 2022 and navigate to the “Extensions” menu.
  2. Choose “Manage Extensions” from the dropdown.
  3. In the “Manage Extensions” window, click on the “Online” tab on the left side.
  4. Use the search bar to find the template. Search for “template onionapi”. See Figure 2 for a visual reference.
  5. Upon locating the template, click the “Download” button.
  6. Visual Studio will download and install the template; a restart may be required for it to become available.

Part 2: Scaffold a New Web API Project

To create a new Web API project using the Visual Studio template, follow these steps:

  1. Open Visual Studio and select Create a new project from the start page or File menu.
  2. In the Create a new project dialog, search for and select the OnionAPI Template and click Next. Refer to Figure 3 for guidance.
  3. In the Configure your new project dialog, name your project (e.g., MyNetcore7WebAPI) and choose a location to save it. Click Create.
  4. The Onion API template will scaffold a new ASP.NET Core Web API project based on the Clean Architecture.

Part 3: Explore the Generated Source Code

Figure 4 showcases a screenshot of the source code created by the OnionAPI template for the sample project MyNetcore7WebAPI. It displays the organization of five projects categorized into three folders: Core, Infrastructure, and Presentation, corresponding to the Clean Architecture layers.

Initially, it may feel overwhelming with numerous projects and layers of dependencies. Here’s a quick navigation guide:

  1. Controllers: Located in the Controllers folder within the WebAPI project. Refer to Figure 5 for assistance. These controllers handle requests and delegate processing to the Handlers.
  2. Handlers: Found in the Features folder within the Application project. See Figure 6 for clarity. Handlers manage business logic and may interact with the DB repository for data operations. The Fluent Validation is integrated to ensure data integrity.
  3. Repositories: Located in the Repositories folder within the Persistence project. Consult Figure 7 for visual guidance. A repository is a design pattern that standardizes data interactions, separating data access from business logic.

Part 4: Test Run the Web API Project

The OnionAPI template creates two REST resources for your convenience. First, the Employees resource serves as a mock API, dynamically generating data using the Bogus library at runtime. To learn more about Bogus, refer to the References section later.

Additionally, the template generates a Positions resource, sourcing data from an actual database table, which is pre-seeded with 1,000 rows of fake data upon the initial project run.

To interact with the REST API using Swagger, follow these steps:

  1. Click on Employees > GET to expand the interface.
  2. Hit the Try it out button.
  3. Input any desired parameters (e.g., search for "Chief" in the employeeTitle field).
  4. Specify the order by column name (e.g., employeeTitle).
  5. Click Execute.
  6. Review the JSON output to appreciate the REST API’s capabilities.

For additional assistance, consult Figure 8 for a visual aid.

If you need help understanding the JSON output, Figure 9 provides a sample screenshot. It illustrates the use of server-side paging for performance. The response body includes a “wrapper” with user-friendly data for easier frontend consumption. Here’s a breakdown of the fields:

  • pageNumber: Pagination index (default is page 1).
  • pageSize: Number of records per page (default is 10).
  • recordsFiltered: Count of records matching the search criteria (e.g., "Chief").
  • recordsTotal: Total number of employees in the database.
  • succeeded: Boolean indicating the response status.
  • message: Friendly error message, if applicable.
  • errors: System error, if any.
  • data: Response data in JSON format.

If you wish to minimize the amount of data sent over the network, specify the desired column names in the Fields area, as depicted in Figure 10. For instance, if the frontend only needs the firstName, lastName, and employeeTitle columns, you can specify those, resulting in a JSON response that includes only these fields in the “Data” section, as illustrated in Figure 11.

The scaffolded source code is rich in features, including examples for modifying data in the Positions resource. Figure 12 showcases methods like POST, GET, PUT, and DELETE to facilitate CRUD operations.

Serilog is integrated into the template to help track WebAPI requests and error events. You can view structured log events in both the output console and text files. Refer to Figure 13 for guidance on finding these logs, enabling you to monitor your codebase effectively.

Screencast

This video tutorial guides you through creating a new ASP.NET Web API project using the OnionAPI template and accessing the API endpoints via the Swagger UI post-launch.

OnionAPI Template in Action

I am thrilled to announce my upcoming blog series, which will focus on developing dynamic and user-friendly web applications using Single Page Application (SPA) architecture and contemporary tools such as Angular 15, Bootstrap 5, and .NET 7 API. The series will feature a comprehensive project demo and multipart blog posts that dive deep into full-stack components, showcasing the latest tools and techniques available.

The WebAPI layer in this blog series will be generated using the powerful OnionAPI template. I’ll provide an in-depth explanation of the generated source code, allowing you to fully appreciate its capabilities. Give it a shot!

Fullstack Angular 15, Bootstrap 5 & NET 7 API: Project Demo

This demo project showcases Angular 15, Bootstrap 5, and .NET 7, featuring server-side pagination, sorting, filtering, and CRUD functionalities.

Summary

If you’re responsible for overseeing development processes, you know how demanding it can be to maintain smooth operations. Governance can be challenging, and finding tools that enhance processes can be difficult. The OnionAPI template is here to help; it aims to boost consistency and reduce delivery time, simplifying your tasks.

Moreover, the OnionAPI template provides boilerplate code for a variety of advanced REST API features, such as data filtering, sorting, shaping, paging, and CRUD operations. These features are designed as base classes, making them easy to inherit and extend for your project’s unique requirements. Don’t let messy code and complex processes hinder your workflow—try the OnionAPI template today and experience a transformation in your development approach.

Thank you for reading! I hope you found this useful. If you want more content, please hit the “Follow” button on my profile. Your support encourages me to keep creating valuable resources for you. Have a wonderful day ahead!

— Fuji Nguyen

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Embracing Mistakes: The Path to Personal Growth and Success

Discover how embracing mistakes can lead to personal growth and success in various aspects of life.

Japan's Unique Approach to Real Estate: Lessons for China

This article explores Japan's unique housing stability amidst China's real estate crisis and the lessons that can be learned.

Unleashing Viral Creativity: Insights from Mr. Beast

Discover how Mr. Beast and Sam Parr generate viral ideas and transform them into engaging content strategies.

Boosting Memory Through Dynamic Physical Activities

Exploring how dynamic physical activities like tree climbing can enhance working memory.

The Impact of Behavior: How Your Manner Can Shape Life Experiences

Explore how your behavior influences interactions and opportunities, emphasizing the importance of presence and mindfulness in everyday life.

How to Stay Agile and Active as You Age: A Kinesiologist's Guide

Discover how to maintain mobility and reduce stiffness as you age with practical tips and exercises for a healthier lifestyle.

Exploring Space: Fascinating Insights from a Sci-Fi Novelist

Discover intriguing facts about space through the eyes of a sci-fi novelist, blending creativity with scientific research.

Navigating Self-Love vs. Self-Coddling: Recognizing the Difference

Explore the fine line between true self-love and self-coddling, with signs to recognize unhealthy patterns.