whalebeings.com

Essential Guide to .NET 6 Web API and Entity Framework Core

Written on

Introduction to .NET 6 in Web Development

The landscape of web development is continuously evolving, and .NET is increasingly becoming a key player in this arena. Many requests for web development projects now specifically seek expertise in .NET, particularly in areas such as Web API and Entity Framework Core. Understanding the core principles of back-end development using .NET can significantly enhance your career prospects, and this tutorial series aims to guide you through that process.

In a short span, you'll discover how to establish a Web API, execute RESTful calls, and store data persistently using Entity Framework Core alongside Code-First Migration, SQL Server, and SQLite. Additionally, you'll learn about implementing the various types of relationships within these databases. This course will provide you with hands-on coding experience at each step, ensuring that by the end, you will be well-equipped to accept any .NET project requests from potential employers.

To get started, all you need is Visual Studio Code, which is available for free. We will use this tool to create our implementations and interact with the Web API via Swagger UI, a convenient interface that simplifies API consumption, thanks to the .NET framework.

Visual Studio Code is compatible with Windows, Mac OS, and Linux. Given that the .NET framework supports multiple platforms, you can follow along using any of these operating systems. Later on, we will leverage SQL Server Express along with SQL Server Management Studio to manage our database, and we will also touch upon SQLite to familiarize you with different database management systems.

The back-end application we will develop is a simple text-based role-playing game (RPG) where users can register (utilizing JSON web tokens for authentication) and create their own characters, such as mages or knights. Players will be able to add skills and weapons to their characters and engage in battles to determine the strongest among them.

I hope you are ready to acquire new skills and take on exciting projects. Let’s get started!

Tools Required

Creating Your First Web API

Once you have installed the .NET SDK and Visual Studio Code, you can create your first .NET application, which will be a Web API. Start by creating a new folder named "dotnet-rpg" (short for "dotnet role-playing game") and open it in VS Code.

If you're not already familiar with Visual Studio Code, feel free to explore its features. It’s also advisable to install a few extensions. The "C# for Visual Studio Code" extension by Microsoft is a must, as it provides essential editing support, syntax highlighting, and IntelliSense, among other features.

Another useful extension is "C# Extensions" by KreativJos, which can enhance your development workflow by adding options to the context menu for creating new C# classes or interfaces. Lastly, I recommend the "Material Icon Theme," which offers a variety of appealing icons.

Now, let’s create our Web API! Open a new terminal window to see the commands available with the dotnet tool. By adding the -h flag, you can view all available commands. The "new" command is what we will use to generate a new .NET project. Additionally, we have the "run" command to execute our application and the "watch" command, which can be combined with "run" to automatically restart the application when any changes are made to the code. This feature is particularly useful as it saves you the hassle of manually restarting the project every time you make an edit.

To see all the available templates, enter the command dotnet new --list. Among the numerous options, we will select the Web API template. To do so, type dotnet new webapi and press enter.

You will notice several files generated in the explorer. Let’s quickly review them.

Generated Files Overview

At the bottom of the generated files, you will find the WeatherForecast class, which is included by default in the Web API project. While we won't be using it extensively, it serves as a useful example for our purposes.

You may also see a prompt suggesting that additional files should be added. Accept this prompt to include the necessary files.

Now, let’s examine the Program class. Notably, in .NET 6, the Startup class for configuration tasks has been integrated directly into Program.cs. This class is responsible for configuring the application's services—essentially reusable components that add functionality to the app.

In this class, we’ll register services that can be used throughout our web service via dependency injection. It also sets up the request processing pipeline, determining how the application responds to HTTP requests, incorporating components like HttpsRedirection and Authorization.

Since .NET 5, Swagger UI configuration is available by default, providing a user-friendly way to test our API. We will utilize this feature in the following sections.

In the .csproj file, you will find the SDK, target framework (in this case, .NET 6), and root namespace. Additionally, there’s a package reference to Swashbuckle.AspNetCore for Swagger UI. Later, we’ll add more packages, such as Entity Framework Core.

The appsettings.json file allows for configuration adjustments, while the launchSettings.json file configures the current environment and application URL, which will direct us to our running web service. You can ignore the obj and bin folders for now; they contain temporary object and final binary files.

A crucial aspect of our project is the Controllers folder. The first controller you will see here is the WeatherForecast demo controller. We will delve into the details of controllers shortly, but for now, keep in mind that we can already invoke the Get() method here.

Executing Your First API Call

To start our application, enter dotnet watch run in the terminal. This will initiate your application with hot reload enabled. Your default browser should open automatically, displaying the Swagger UI, which will assist us in testing our Web API.

In Swagger, you will see the WeatherForecast Controller listed, and by entering the corresponding URL in the address bar, you can access the controller directly.

Now, let’s explore how to make our own web service.

Creating a New Controller and Models

At this point, you have learned how to create a Web API project in .NET from scratch and perform your first API call. In the upcoming sections, we will develop a new controller and models for our RPG characters. We will also transition our synchronous calls into asynchronous ones, utilize Data Transfer Objects (DTOs), and restructure our Web API to adhere to best practices.

But first, let’s examine the Model-View-Controller (MVC) pattern, which serves as the foundation for our application.

Understanding the MVC Pattern

The Model-View-Controller (MVC) pattern is a software design strategy that organizes related program logic into three interconnected components. Let's break down what each of these components represents and how they work together.

  1. Model: This represents the data. For instance, a character in our RPG serves as a model, encompassing properties such as Id, name, hit points, attributes, and skills.
  2. View: This is what the user interacts with. It could be an HTML representation, plain text, or even advanced 3D graphics, depending on the game's design. In essence, the view is the graphical user interface (GUI).
  3. Controller: This is where the logic resides. It manipulates the data or model, handling operations such as creating, updating, or deleting data. In our case, it will manage the Web API that interfaces with our data.

Since we won’t have a traditional view in our application, we will build our application in a sequence starting with the model and then the controller, iterating between the two as necessary.

Now, let's move on to creating our first models.

Creating New Models

We will need to create models for our RPG character and character classes (e.g., Barbarian, Mage, Necromancer).

Start by creating a Models folder. Next, create a new class for the character model within this folder. If you have the "C# Extensions" installed, you can easily add a new C# class via a right-click; otherwise, create a new file manually.

Once you have created the class, let’s define its properties. We will also need to establish an RpgClass property to indicate the type of character. To do this, we will create a new enum for character classes.

In the Models folder, add a new C# enum called RpgClass. You can include various role-playing classes like Knight, Mage, and Cleric. For simplicity, we will set the default to Knight, but you can choose as you see fit.

With the RpgClass enum established, we can now incorporate it into the Character model.

Next, let’s proceed to create a new controller and implement a GET method to retrieve our first RPG character.

Creating the Character Controller

To add a new controller, create a new C# class within the Controllers folder. Though the C# Extension allows for creating an "API Controller" class directly, we will manually implement the necessary steps for clarity.

Name this class CharacterController. First, we must ensure it derives from ControllerBase, which requires referencing Microsoft.AspNetCore.Mvc. This base class is essential for an MVC controller without view support.

Since we are developing an API, view support isn't necessary, but if we wanted to include it in the future, we could derive from Controller instead.

Next, let’s add some attributes. Start with the [ApiController] attribute to indicate that this class serves HTTP API responses. This attribute also activates several API-specific features, such as attribute routing and automatic HTTP 400 error responses if the model encounters issues.

Following this, we will implement attribute routing by adding the [Route] attribute below the [ApiController] attribute. This will allow us to find this controller during web service calls.

The string in the [Route] attribute should be "api/[controller]", meaning that this controller can be accessed via the URL pattern "api" followed by the controller’s name—in this case, "Character."

Now, let’s delve into the body of our C# class. First, we will create a static mock character to return to the client. This requires adding a reference to the dotnet_rpg.Models namespace.

Next, we will implement the Get() method to retrieve our game character. We will return an IActionResult, which enables us to send specific HTTP status codes along with the requested data back to the client. Using Ok(knight), we can return a 200 OK status along with our mock character.

Now that the code is ready, let’s test it by restarting the application with dotnet watch run.

Swagger UI will initially display an error, but we can also attempt to access our web service method through the browser by entering the appropriate route for the CharacterController.

Back to Swagger, we can open the Developer Tools to inspect the Network Tab for any issues. If actions require explicit HttpMethod bindings, we’ll need to add an [HttpGet] attribute to our Get() method.

After adding this attribute, we should also adjust the return type to ActionResult of type Character. If we save these changes, we may need to restart our application.

With these adjustments made, we should now see all the desired information in Swagger. This will include our Character class and the RpgClass enum.

To enhance the clarity of our enum, we can configure the JsonConverter to display string names instead of numbers by adding the attribute JsonStringEnumConverter above the enum definition.

Finally, after restarting the application, we should be able to test the Get() method without issues.

Conclusion

This concludes the first part of our tutorial series on building a .NET 6 Web API and utilizing Entity Framework Core. I hope you found this information helpful! To stay updated on the next installments, consider subscribing to my newsletter or following me on Medium.

In the upcoming sections, we will cover topics such as attribute routing, HTTP methods, adding new characters with POST, asynchronous calls, and much more!

Let's continue this journey together!

Enjoy more in-depth .NET & Blazor tutorials on YouTube.

Subscribe for coding tutorials and updates!

Connect with me on Twitter, LinkedIn, or Medium.

Subscribe to my newsletter for early access to tutorials and courses related to .NET, Blazor, and beyond!

Level Up Coding

Thank you for being part of our community! Explore more content in the Level Up Coding publication.

The first video, "Intro to Web API in .NET 6 - Including Minimal APIs, Swagger, and more," provides an excellent introduction to Web API concepts in .NET 6. It covers essential topics like Minimal APIs, Swagger integration, and gives practical examples that will be beneficial as you progress through your learning.

The second video, "Industry Level REST API using .NET 6 – Tutorial for Beginners," serves as a comprehensive guide for beginners interested in developing industry-standard REST APIs with .NET 6. It walks through the core concepts and provides hands-on examples, ensuring a solid foundation for your back-end development journey.

Share the page:

Twitter Facebook Reddit LinkIn

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

Recent Post:

Avoid These Misguided Strategies for Startup Growth

Discover three common strategies that could harm your startup's growth, and learn more effective approaches.

Maximize Your Productivity: Top Strategies for Success

Explore effective methods to enhance productivity and clarity in your life.

Mysterious Sounds from the Depths of Outer Space Unveiled

Discover the intriguing origins of mysterious sounds detected in outer space, revealing more about our universe's secrets.