Tutorial: Create a web API with ASP.NET Core

  Web   Asp.net  Web Api  DreamozTech  
This tutorial teaches the basics of building a web API with ASP.NET Core.
Tutorial Create A Web Api With Asp Net Core
Tutorial Create A Web Api With Asp Net Core

In this tutorial, you learn how to:

Create a web API project.
Add a model class and a database context.
Scaffold a controller with CRUD methods.
Configure routing, URL paths, and return values.
Call the web API with Postman.

At the end, you have a web API that can manage "to-do" items stored in a database.


Overview

This tutorial creates the following API:


API                                         Description          Request body        Response body
GET /api/todoitems   Get all to-do items          None      Array of to-do items
GET /api/todoitems/{id}   Get an item by ID          None         To-do item
POST /api/todoitems     Add a new item            To-do item         To-do item       
PUT /api/todoitems/{id} Update an existing item     To-do item             None
DELETE /api/todoitems/{id}    Delete an item             None             None


Create a web project

From the File menu, select New > Project.

Select the ASP.NET Core Web API template and click Next.

Name the project TodoApi and click Create.

In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core 5.0 are selected. Select the API template and click Create.


Test the project

The project template creates a WeatherForecast API with support for Swagger.


Press Ctrl+F5 to run without the debugger.

Visual Studio displays the following dialog when a project is not yet configured to use SSL:

Select Yes if you trust the IIS Express SSL certificate.

The following dialog is displayed:

Select Yes if you agree to trust the development certificate.

For information on trusting the Firefox browser, see Firefox SEC_ERROR_INADEQUATE_KEY_USAGE certificate error.

Visual Studio launches:

The IIS Express web server.
The default browser and navigates to https://localhost:<port>/swagger/index.html, where <port> is a randomly chosen port number.

The Swagger page /swagger/index.html is displayed. Select GET > Try it out > Execute. The page displays:

The Curl command to test the WeatherForecast API.
The URL to test the WeatherForecast API.
The response code, body, and headers.
A drop down list box with media types and the example value and schema.

If the Swagger page doesn't appear, see the GitHub issue.

Swagger is used to generate useful documentation and help pages for web APIs. This tutorial focuses on creating a web API. For more information on Swagger, see ASP.NET Core web API documentation with Swagger / OpenAPI.

Copy and paste the Request URL in the browser: https://localhost:<port>/WeatherForecast

JSON similar to the following is returned:

JSON

[
    {
        "date": "2019-07-16T19:04:05.7257911-06:00",
        "temperatureC": 52,
        "temperatureF": 125,
        "summary": "Mild"
    },
    {
        "date": "2019-07-17T19:04:05.7258461-06:00",
        "temperatureC": 36,
        "temperatureF": 96,
        "summary": "Warm"
    },
    {
        "date": "2019-07-18T19:04:05.7258467-06:00",
        "temperatureC": 39,
        "temperatureF": 102,
        "summary": "Cool"
    },
    {
        "date": "2019-07-19T19:04:05.7258471-06:00",
        "temperatureC": 10,
        "temperatureF": 49,
        "summary": "Bracing"
    },
    {
        "date": "2019-07-20T19:04:05.7258474-06:00",
        "temperatureC": -1,
        "temperatureF": 31,
        "summary": "Chilly"
    }
]

Update the launchUrl

In Properties\launchSettings.json, update launchUrl from "swagger" to "api/todoitems":

JSON

"launchUrl": "api/todoitems",

Because Swagger will be removed, the preceding markup changes the URL that is launched to the GET method of the controller added in the following sections.


Add a model class

A model is a set of classes that represent the data that the app manages. The model for this app is a single TodoItem class.

In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models.

Right-click the Models folder and select Add > Class. Name the class TodoItem and select Add.

Replace the template code with the following:

C#

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}
The Id property functions as the unique key in a relational database.

Model classes can go anywhere in the project, but the Models folder is used by convention.


Add a database context

The database context is the main class that coordinates Entity Framework functionality for a data model. This class is created by deriving from the Microsoft.EntityFrameworkCore.DbContext class.


Add NuGet packages

From the Tools menu, select NuGet Package Manager > Manage NuGet Packages for Solution.
Select the Browse tab, and then enter Microsoft.EntityFrameworkCore.InMemory in the search box.
Select Microsoft.EntityFrameworkCore.InMemory in the left pane.
Select the Project checkbox in the right pane and then select Install.


Call the web API with JavaScript

Add authentication support to a web API
ASP.NET Core Identity adds user interface (UI) login functionality to ASP.NET Core web apps. To secure web APIs and SPAs, use one of the following:

Azure Active Directory
Azure Active Directory B2C (Azure AD B2C)
IdentityServer4

IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core. IdentityServer4 enables the following security features:

Authentication as a Service (AaaS)
Single sign-on/off (SSO) over multiple application types
Access control for APIs
Federation Gateway


Are you looking to create valuable SEO content at an affordable price? Our SEO platform allows you to be creative, while still helping you boost your SEO ranking. Sign up today to find out more.

Leave a message

Full Name
Email
Mobile
Description