Featured Article

Complete Asp Net Core Api Tutorial Step By Step Guide

Kenneth Jul 13, 2026

Embarking on a journey to create robust and scalable web APIs? ASP.NET Core has you covered. This popular, cross-platform framework offers a powerful way to build high-performance, cloud-based, and internet-connected solutions. Here, we'll guide you through an engaging ASP.NET Core API tutorial, helping you develop a solid understanding of this technology.

Tutorial: Create C# ASP.NET Core web application - Visual Studio (Windows)
Tutorial: Create C# ASP.NET Core web application - Visual Studio (Windows)

ASP.NET Core's modular approach and extensive ecosystem make it an excellent choice for both simple and complex applications. It's not just about creating APIs; it's about building maintainable, testable, and efficient systems. Let's dive in and explore what sets ASP.NET Core apart, and how to get started with your first API project.

ASP.NET Core Route Tooling
ASP.NET Core Route Tooling

Setting Up Your Development Environment

Before we dive into creating APIs, ensure you have the right tools in place. ASP.NET Core runs on .NET Core, which is-platform agnostic, meaning it works on Windows, Linux, and macOS.

a web api with asp net core, net 6 0 build a web api with asp net core
a web api with asp net core, net 6 0 build a web api with asp net core

First, install the .NET SDK from the official Microsoft website. Once installed, verify it by opening a terminal or command prompt and typing:

dotnet --version

The installed version should be displayed. Now, we're ready to create our first ASP.NET Core API project.

ASP.Net Projects with Source Code
ASP.Net Projects with Source Code

Creating a New ASP.NET Core API Project

The dotnet new command creates new .NET projects. To create a new API project, run:

dotnet new webapi -n MyApiProject

Replace MyApiProject with the desired name for your project. Then, navigate into the new project directory:

Building an ASP.NET Web API with ASP.NET Core | Toptal®
Building an ASP.NET Web API with ASP.NET Core | Toptal®

cd MyApiProject

Run the application using:

dotnet run

Your API is now up and running at https://localhost:5001.

Exploring the Scaffolded Project Structure

REST API Methods Explained in 60 Seconds
REST API Methods Explained in 60 Seconds

ASP.NET Core provides a clean, intuitive project structure. Here's a brief overview:

  • Controllers: Contains controller classes that handle API requests and responses.
  • Models: Holds models that represent your data.
  • Startup.cs: The entry point of your application, where services are configured.
  • Program.cs: The entry point for hosting the web application.
Tutorial: Host a RESTful API with CORS - Azure App Service
Tutorial: Host a RESTful API with CORS - Azure App Service
ASP.NET Web API Tutorials For Beginners and Professionals
ASP.NET Web API Tutorials For Beginners and Professionals
Asp.net Core web API Tutorial: C# web API .Net Core Example
Asp.net Core web API Tutorial: C# web API .Net Core Example
the api roadmap is shown in this graphic
the api roadmap is shown in this graphic
教學課程:使用 ASP.NET Core 建立控制器型 Web API
教學課程:使用 ASP.NET Core 建立控制器型 Web API
Deploy ASP.NET Core Web Apps to Azure App Service
Deploy ASP.NET Core Web Apps to Azure App Service
ASP.NET and MVC Tutorial Guide
ASP.NET and MVC Tutorial Guide
owasp top 10 web application vulnerabilities
owasp top 10 web application vulnerabilities
ASP.NET Tutorial | ASP.NET Core Tutorial For Begginers
ASP.NET Tutorial | ASP.NET Core Tutorial For Begginers

Understanding these components will help you navigate and modify the project as needed.

Building Your First API Controller

Now that we have a basic project set up, let's create our first API controller. In the Controllers folder, create a new file called WeatherForecastController.cs.

Add the following code to the newly created file:

```csharp using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace MyApiProject.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly List<WeatherForecast> _forecasts = new List<WeatherForecast> { new WeatherForecast { Date = DateTime.Now.AddDays(1), TemperatureC = 25 }, new WeatherForecast { Date = DateTime.Now.AddDays(2), TemperatureC = 28 }, // Add more forecast data... }; [HttpGet] public IEnumerable<WeatherForecast> Get() { return _forecasts; } } public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public string Summary { get; set; } } } ```

This code creates a simple controller with a single GET action that retrieves a list of weather forecasts. To test this, run the application and navigate to https://localhost:5001/weatherforecast in your browser. You should see the list of forecasts.

Exploring Route Attributes

The [ApiController] and [Route("[controller]")] attributes control how the API routes work. By combining these attributes with the HttpGet attribute on the action method, we've created a simple but powerful API endpoint.

The [ApiController] and [Route("[controller]")] attributes are shorthand for applying the [Produces("application/json")], [Consumes("application/json")], and other attributes, making it easier to handle API-specific aspects of your controllers.

Securing Your ASP.NET Core API

ASP.NET Core offers built-in support for various authentication schemes, such as JWT (JSON Web Tokens) and cookie-based authentication. Let's briefly explore JWT authentication for securing our API.

The Microsoft.AspNetCore.Authentication.JwtBearer library provides the necessary functionalities for JWT authentication. First, install the package via:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Then, register the authentication services in the Startup.cs file's ConfigureServices method:

```csharp services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); ```

Finally, apply the [Authorize] attribute to the WeatherForecast controller to require authentication for accessing it:

```csharp [Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { // ... } ```

This ensures that only authenticated users can access the weather forecast data in our API.

Generating and Handling Tokens

To handle token generation and storage, create a new API controller called AuthController.cs. Add the following code to create a simple token endpoint:

```csharp using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace MyApiProject.Controllers { [ApiController] [Route("[controller]")] public class AuthController : ControllerBase { private readonly IConfiguration _configuration; public AuthController(IConfiguration configuration) { _configuration = configuration; } [HttpPost] public ActionResult Login(string username, string password) { // Here you should validate the username and password against a persistence store // For simplicity, we assume a valid user in this example if (username == "validuser" && password == "secretpassword") { var claims = new List { new Claim(ClaimTypes.Name, username), // Add more claims as needed... }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["Jwt:ExpireDays"])); var token = new JwtSecurityToken( _configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: expires, signingCredentials: credentials ); return new TokenResponse(token.ToString(), expires); } return Unauthorized(); } } public class TokenResponse { public string Token { get; set; } public DateTime Expires { get; set; } } } ```

Test the new authentication endpoint by sending a POST request to https://localhost:5001/auth with the JSON body:

```json { "username": "validuser", "password": "secretpassword" } ```

The API should return a JSON response containing the generated JWT token, which can then be used to authenticate subsequent API requests.

ASP.NET Core's modular and extensible nature allows for easy integration of various authentication schemes and additional features to further secure your APIs.

As you've seen throughout this tutorial, ASP.NET Core offers a rich ecosystem for building powerful, scalable, and maintainable web APIs. By understanding and leveraging the framework's capabilities, you can create robust and efficient solutions tailored to your needs. Happy coding, and here's to your next API adventure!