Skip to content

kevinhellos/dotnet-web-api

Repository files navigation

dotnet web api

Tutorial on building a web API using C# with Microsoft .NET
For this tutorial, we will be using dotnet 6..

What you need to have

  • dotnet installed. If you do not have installed, install it from here (dotnet 6).
  • Visual Studio (purple icon) NOT vscode (blue icon). Install it from here.

Quick Tutorial

  • Download the Menus API.sln from here.
  • Double click to run the solution.

Manual Tutorial

Step 1 - Project Setup

  • launch Visual Studio and create a new project
  • choose API as the template. On the dropdown menu, ensure it selects C#. Once done, click continue image
  • On the Target Framework dropdown menu, ensure it selects .NET 6.0. On the Advanced, follow the settings as per image below. Once done, click continue image
  • For the purpose of this tutorial, my Project name will be Menus API as we will be working with menus. Feel free to choose your own directory for Location of the project. Once done, click Create image
  • When the project has been successfully created, your Visual Studio Solution Explorer should look something like this. Your Solution Explorer may look different, but it is alright image

Step 2 - Deleting Boilerplate Codes

  • Inside the Solution Explorer, delete:
    -- Controllers/WeatherForecastController.cs
    -- WeatherForecast.cs

Step 3 - Creating the MenusController

  • Inside the Controllers folder, create a new controller. Right click on Controllers folder,Add -> New Class -> ASP.NET Core -> Controller Class. For the name, type MenusController.
  • Inside the MenusController.cs, replace the whole source code with the codes below
// MenusController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Menus_API.Controllers
{
    [ApiController]
    [Route("/api/Menus")] // defines the API route. In this case localhost:<port_number>/api/Menus

    public class MenusController : ControllerBase
    {
        [HttpGet(Name = "GetMenus")]
        public IEnumerable<Menu> Get()
        {
            // Sample data of menu items
            // Creating a Menu List containg Menu Objects
            var menus = new List<Menu>
            {
                new Menu { Id = 1, Name = "Breakfast Menu", Price = 10.99, Category = "Breakfast" },
                new Menu { Id = 2, Name = "Lunch Menu", Price = 15.99, Category = "Lunch" },
                new Menu { Id = 3, Name = "Dinner Menu", Price = 20.99, Category = "Dinner" }
                // Add more menu objects as needed
            };
            return menus;
        }

    }

    // Creating a Menu class
    public class Menu
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Category { get; set; }
    }

}

Step 4 - Configuring Project

  • Inside the Properties folder, open the launchSettings.json
  • Replace all contents of launchSettings.json with the following codes
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:33341",
      "sslPort": 44358
    }
  },
  "profiles": {
    "Menus_API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "/api/Menus",
      "applicationUrl": "https://localhost:7019;http://localhost:5009",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": true
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "/api/Menus",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
  • Inside the Solution Explorer folder, open the Program.cs
  • Replace all contents of Program.cs with the following codes
// Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    // app.UseSwagger();
    // app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
  • Click Run (play button) to build and launch the project
    image
  • If your project is setup and configured correctly, you should see the following on your browser. Url would be localhost:YOUR_PORT/api/menus
    image

End of tutorial
Source code has also been provided in this repository.

About

Tutorial on building a web API using C# with Microsoft .NET

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages