Table of Contents

Introduction

In this tutorial, we will build .NET 6 Web API that uses Entity Framework core and SQL to create API endpoints. It will allow clients to perform CRUD operations in API on the data stored in the database.

In our demo application, we will be using the database first approach. We will start with creating a table in the SQL database and then use an entity framework to create DBContext and Model.

What is Web API?

A Web API, or Application Programming Interface, is a platform designed to develop HTTP services that can be accessed by various client-side applications such as mobile devices, web browsers, and desktop applications. It acts as a medium for multiple applications to exchange data and interact with each other.

What is Web API?

Developers can create functions that can be requested through HTTP calls with API. This function allows you to save or retrieve data for your clients, enabling them to perform certain tasks and access specific information that is made available to them through the API.

Key features of API

  • Supports HTTP verbs like GET, POST, PUT, DELETE, etc., which allows clients to perform different actions on the data
  • Supports default responses such as XML and JSON, standard formats which help exchange data between the client and the server.
  • API can define custom data which allows you to tailor the data as per client requirements
  • APIs are either self-hosted or hosted by third parties, which means you have flexibility in using them.
  • It allows easy authorization and authentication, which helps control access to API crud operations and protects your data.
  • API is an ideal platform for building RESTful services for designing web services that are scalable, flexible, and easily maintained.

Why do we need Web API?

People nowadays use multiple devices such as smartphones, tablets, and iPhones; therefore, more than a web-based application is needed to reach out to all users. We need an API to expose all these service data to all the different device apps and browsers. Adding a web API project makes it easier to bridge the two ends, making it easier to manage and update.

In this case, we need a Web API to manage the database interactions and business logic between a website, an Android app, and an iOS app.

All three applications can communicate with the database through the Web API project, which handles all database interactions and ensures that the database is not directly accessible through the websites or applications.

By using a Web API, we can ensure secure and efficient communication between the different applications and devices, making it an essential tool in modern application development.

What's new in .NET 6?

Let us have a look at some of the major highlights.

  • Hot Reloading allows developers to modify the user interface while the application is still running. Changes are reflected in real-time without rebuilding or starting the app.
  • Minimal APIs for developers to build lightweight services without needing templates or controllers, using extension methods of “EndpointConcentionBuilder” in the Startup or Program class.
  • The HTTP logging middleware can log HTTP request and response information like headers, body, and properties to enhance debugging and monitoring
  • The Blazor web framework used for building interactive web applications with c# has improved performance, event binding, and support for pre-rendering components.
  • ASP.NET Core program and Startup classes are merged to simplify the code structure.
  • Support for cloud-native development through integration with Kubernetes and other cloud platforms.
  • Enhanced JSON support through the introduction of a new source generator
  • .NET Core has now improved support for gRPC and GraphQL APIs.
    The use of OpenSSL 3 and support for runtime defense-in-depth mitigations enhance the security of the .NET core.
  • Support for Single-file applications without extraction on Windows, macOS, and Linux.
  • The re-written FileStream improves performance for I/O operations, especially for file I/O.
  • Improved source code generation with a new source generator framework.
  • Improved .NET MAUI (Multi-platform App UI) support for building cross-platform mobile and desktop apps.
  • Improvements to the .NET runtime include enhanced garbage collection, improved ARM-based platforms performance, and hardware intrinsics support.
  • Entity Framework Core has improved support for Cosmos DB and a new LINQ syntax for querying nested JSON data.
  • Visual Studio tooling has improved with new project templates and integration with GitHub.

Prerequisites: Web API in .NET 6.0

  • Visual Studio 2022.
  • .NET SDK 6.0.
  • Sql-Server.
    • Create Project

      Start Visual Studio and create a new project with the type ASP.NET Core Web API and click Next.

      Create a new project with .net

      Enter the project name ProductCrudAPI, select the location where you want to save your project, and click Next.

      configure new project with .net

      Select .Net 6.0 (Long-term support) as a framework. Fill in the required information as shown in the below image, and click on Create.

      add additional information .net

      Once you click on Create, a Web API project will be created.

      Create Project with .net

      Add NuGet Packages

      To use the entity framework core in our project, we need to install two NuGet packages:

      • Microsoft.EntityFrameworkCore.Tools
      • Microsoft.EntityFrameworkCore.SqlServer
        • Follow the below instructions to install NuGet packages.
          Right-click on Dependencies and select Manage NuGet Packages.

          Add NuGet Packages with .net

          Microsoft.EntityFrameworkCore.Tools
          Select the Browse tab and search for Microsoft.EntityFrameworkCore.Tools and install its latest stable version.

          Add NuGet Packages with .net

          Microsoft.EntityFrameworkCore.SqlServer
          Once the above package is installed, Search for Microsoft.EntityFrameworkCore.SqlServer and install its latest stable version.

          Add NuGet Packages with .net

          Create SQL Database and Table.

          Moving to the next section of the Web API in .NET 6.0 Tutorial, create New Database ProductDB in SQL, and execute the below script to create a Product table.

          Copy Text
          USE [ProductDB]
          GO
          
          SET ANSI_NULLS ON
          GO
          
          SET QUOTED_IDENTIFIER ON
          GO
          
          CREATE TABLE [dbo].[Products](
          	[Id] [int] IDENTITY(1,1) NOT NULL,
          	[Name] [varchar](50) NOT NULL,
          	[Description] [varchar](250) NULL,
          	[Price] [decimal](18, 2) NOT NULL,
          PRIMARY KEY CLUSTERED 
          (
          	[Id] ASC
          )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
          ) ON [PRIMARY]
          GO
          

          Create DB Context and Model

          Now, let’s move on to the next step of our web API tutorial, where we will create the DBContext and Model.

          We are using the database first approach of entity framework.
          We have created a database table, and using the Scaffold-DbContext command of the entity framework; we will create the required class in the C# project.

          Open Package Manager Consol (Tool => Package Manager => Package Manager Consol) and run below command:

          Copy Text
          Scaffold-DbContext "Server=SERVERNAME;Database=ProductDB;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

          Replace SERVERNAME with your database server name.

          Create DB Context and Model with .net

          Once this command is executed, the Model folder is created in the project solution. Model folder contains two files, ProductDBContext.cs and Product.cs.

          Create DB Context and Model with .net

          ProductDBContext.cs is responsible for database interaction, and Product.cs is a model of the Products table.

          Remove OnConfiguring() method from ProductDBContext.cs; it contains a database connection string and is not a good practice. We will add the connection string in the appsettings.json file.

          Also remove ProductDBContext() constructor from this file.

          Build a .NET application is easier and hustle-free with Bacancy!
          Hire NET developer who will help you meet your project requirements efficiently with commendable problem-solving skills.

          Configure DB Connection

          Add database connection string in appsettings.json file.

          Copy Text
          {
            "Logging": {
              "LogLevel": {
                "Default": "Information",
                "Microsoft.AspNetCore": "Warning"
              }
            },
            "AllowedHosts": "*",
            "ConnectionStrings": {
              "ProductDB": "Server=SERVERNAME;Database=ProductDB;Integrated Security=True;"
            }
          }
          

          Replace SERVERNAME with your database server name.

          As we are using the .Net 6 version, we need to make the required configuration changes in Program.cs file. Microsoft eliminates Startup.cs in .Net 6. In the previous .Net version, Startup.cs was used for configurations.

          Add below lines in Program.cs. Please refer to the below image for this.

          Copy Text
          var connectionString = builder.Configuration.GetConnectionString("ProductDB");
          builder.Services.AddDbContextPool(option =>
          option.UseSqlServer(connectionString)
          );
          

          Also, add the below lines at the top of the Program.cs.

          Copy Text
          using Microsoft.EntityFrameworkCore;
          using ProductAPI.Models;
          
          Configure DB Connection with .net

          Add Products Controller

          Add a new empty API controller ProductsController.cs under the controller folder.

          Add Products Controller with .net Add Products Controller with .net

          Bacancy is not an option. Bacancy is a reliable choice!
          Are you looking for a leading NET development company to develop your dream product? We are here for you! Trust your choice. Connect Now!

          Add Methods in ProductsController

          In ProductsController.cs, we will add GET, POST, PUT, and DELETE endpoints to achieve CRUD operations.

          Please use the below code in your ProductsController.cs.

          Copy Text
          using Microsoft.AspNetCore.Mvc;
          using Microsoft.EntityFrameworkCore;
          using ProductCRUDAPI.Models;
          
          namespace ProductCRUDAPI.Controllers
          {
              [Route("api/[controller]")]
              [ApiController]
              public class ProductsController : ControllerBase
              {
                  private readonly ProductDBContext _context;
          
                  public ProductsController(ProductDBContext context)
                  {
                      _context = context;
                  }
          
                  [HttpGet]
                  public async Task<IEnumerable<Product>> Get()
                  {
                      return await _context.Products.ToListAsync();
                  }
          
                  [HttpGet("{id}")]
                  public async Task<IActionResult> Get(int id)
                  {
                      if (id < 1)
                          return BadRequest();
                      var product = await _context.Products.FirstOrDefaultAsync(m => m.Id == id);
                      if (product == null)
                          return NotFound();
                      return Ok(product);
          
                  }
          
                  [HttpPost]
                  public async Task<IActionResult> Post(Product product)
                  {
                      _context.Add(product);
                      await _context.SaveChangesAsync();
                      return Ok();
                  }
          
                  [HttpPut]
                  public async Task<IActionResult> Put(Product productData)
                  {
                      if (productData == null || productData.Id == 0)
                          return BadRequest();
          
                      var product = await _context.Products.FindAsync(productData.Id);
                      if (product == null)
                          return NotFound();
                      product.Name = productData.Name;
                      product.Description = productData.Description;
                      product.Price = productData.Price;
                      await _context.SaveChangesAsync();
                      return Ok();
                  }
          
                  [HttpDelete("{id}")]
                  public async Task<IActionResult> Delete(int id)
                  {
                      if (id < 1)
                          return BadRequest();
                      var product = await _context.Products.FindAsync(id);
                      if (product == null) 
                          return NotFound();
                      _context.Products.Remove(product);
                      await _context.SaveChangesAsync();
                      return Ok();
          
                  }
              }
          }

          Launch API

          Finally, we are done with Web API in .NET 6.0 tutorial. Now, it’s time to launch this API, press F5. As we are using Swagger UI, we can execute API directly.

          We can see GET, POST, PUT AND DELETE under Products. We can execute different API methods from this page itself.

          Launch API with .net

          Github Repository: Web API in .NET 6.0 Example

          Here’s the source code of Web API in .NET 6.0 example. Feel free to clone the repository and play around with the code. Start developing your demo application and learn how to build a CRUD operation.

          Conclusion

          So, this was all about how to develop Web API in .NET 6.0. I hope the tutorial helped you to begin with building a basic CRUD operation application using .NET. If you have any questions or feedback, feel free to contact us.

Utilize Our .NET Development Services

Get hand-selected expert engineers to supplement your team for scalable, feature-rich, and cost-effective enterprise solutions.

BOOK A 30 MIN CALL

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?