NATIONAL ECONOMICS UNIVERSITY
SCHOOL OF INFORMATION TECHNOLOGY AND DIGITAL ECONOMICS
CHAPTER IV
ASP.NET CORE API - Controller based
PHAM THAO
OUTLINE
SETUP ASP.NET AND WEB DEVELOPMENT
CREATE A NEW PROJECT
ASP.NET Core Web API – Minimal API
POST
GET
PUT
DELETE
MapGroupAPI
Use TypedResults API
Prevent over-posting
Call from Client
ASP.NET Core Web API – Controller based
CREATE A NEW PROJECT
ASP.NET is a popular web-development framework
for building web apps on the .NET platform.
ASP.NET Core is the open-source version of ASP.NET,
that runs on macOS, Linux, and Windows. ASP.NET
Core was first released in 2016 and is a re-design of
earlier Windows-only versions of ASP.NET.
ASP.NET Core is designed to allow runtime components, APIs,
compilers, and languages evolve quickly, while still providing a
stable and supported platform to keep apps running.
Multiple versions of ASP.NET Core can exist side by side on the
same server. Meaning one app can adopt the latest version, while
other apps keep running on the version they were tested on.
ASP.NET Core provides various support lifecycle options to meet
the needs of your app.
https://learn.microsoft.com/vi-vn/aspnet/core/tutorials/min-web-api?view=aspnetcore-7.0&tabs=visual-studio
CREATE A NEW PROJECT
ASP.NET Core Web API:
This template is designed for building RESTful APIs
without server-rendered views.
It includes controllers that respond to HTTP requests
and return data in JSON or other formats.
Perfect for creating backend services or APIs that serve
data to various client applications, such as web, mobile, or
desktop apps.
It focuses on data exchange and does not include views
or HTML rendering capabilities.
ASP.NET CORE WEB API
Minimal API
Minimal APIs are architected to
create HTTP APIs with minimal
dependencies. They are ideal for
microservices and apps that want to
include only the minimum files,
features, and dependencies in
ASP.NET Core.
Controller-based APIs
ASP.NET CORE WEB API – MINIMAL API
Minimal API
Minimal APIs are
architected to create
HTTP APIs with minimal
dependencies. They are
ideal for microservices
and apps that want to
include only the
minimum files, features,
and dependencies in
ASP.NET Core.
Controller-based APIs
ASP.NET CORE WEB API – MINIMAL API
ASP.NET CORE WEB API – MINIMAL API
Add NuGet packages
Microsoft.EntityFrameworkCore.InMemory
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
THE MODEL AND DATABASE CONTEXT CLASSES
In the project folder, create a
file named Todo.cs with the
following code:
The preceding code creates
the model for this app.
A model is a class that
represents data that the app
manages.
ADD THE API CODE
The following var builder = WebApplication.CreateBuilder(args);
highlighted code adds builder.Services.AddDbContext<TodoDb>(opt =>
the database context opt.UseInMemoryDatabase("TodoList"));
to the dependency
injection builder.Services.AddDatabaseDeveloperPageException
(DI) container and Filter();
enables displaying var app = builder.Build();
database-related
exceptions:
The following code in Program.cs creates an HTTP POST endpoint /todoitems that adds data to the in-memory database:
ADD THE API CODE
The following code in app.MapPost("/todoitems", async (Todo todo, TodoDb
Program.cs creates an db) => { db.Todos.Add(todo); await
HTTP POST endpoint db.SaveChangesAsync();
/todoitems that adds
data to the in- return Results.Created($"/todoitems/{todo.Id}",
memory database: todo); });
Run the app. The
browser displays a
404 error because
there is no longer a /
endpoint.
The following code in Program.cs creates an HTTP POST endpoint /todoitems that adds data to the in-memory database:
ADD THE API CODE
The following code in app.MapGet("/todoitems", async (TodoDb db) =>
Program.cs creates an await db.Todos.ToListAsync());
HTTP POST endpoint app.MapGet("/todoitems/complete", async (TodoDb
/todoitems that adds db) => await db.Todos.Where(t =>
data to the in-
t.IsComplete).ToListAsync());
memory database:
app.MapGet("/todoitems/{id}", async (int id, TodoDb
Run the app. The db) => await db.Todos.FindAsync(id) is Todo todo ?
browser displays a Results.Ok(todo) : Results.NotFound());
404 error because
there is no longer a /
endpoint.
INSTALL POSTMAN TO TEST THE APP
• Install Postman
RUN POST MAN
Run Post Man
{
"name":"walk dog", "isComplete":true
}
POST
POST
EXAMINE THE PUT ENDPOINT
This method is similar to the This sample uses an in-memory database
MapPost method, except it uses that must be initialized each time the app is
HTTP PUT. A successful response started. There must be an item in the
returns 204 (No Content). database before you make a PUT call. Call
According to the HTTP GET to ensure there's an item in the
specification, a PUT request database before making a PUT call.
requires the client to send the
entire updated entity, not just the Update the to-do item that has Id = 1 and
changes. set its name to "feed fish":
To support partial updates, use
HTTP PATCH.
EXAMINE THE PUT ENDPOINT (UPDATE)
app.MapPut("/todoitems/{id}", async (int id, Todo Update the to-do item
inputTodo, TodoDb db) => { var todo = await that has Id = 1 and set
db.Todos.FindAsync(id); its name to "feed fish":
if (todo is null) return Results.NotFound();
todo.Name = inputTodo.Name; { "id": 1, "name": "feed
todo.IsComplete = inputTodo.IsComplete;
fish", "isComplete":
false }
await db.SaveChangesAsync();
return Results.NoContent(); });
DELETE
app.MapDelete("/todoitems/{id}", async (int id, Use Postman to delete a to-
TodoDb db) =>
do item:
{
if (await db.Todos.FindAsync(id) is Todo Set the method to DELETE.
todo)
{
Set the URI of the object to
db.Todos.Remove(todo);
delete (for example
https://localhost:5001/todoit
await db.SaveChangesAsync();
ems/1).
return Results.NoContent();
} Select Send.
return Results.NotFound();
});
USE THE MAPGROUP API
The sample app code repeats the The preceding code has the following changes:
todoitems URL prefix each time it
sets up an endpoint. Adds var todoItems =
APIs often have groups of
app.MapGroup("/todoitems"); to set up the group
endpoints with a common URL using the URL prefix /todoitems.
prefix, and
the MapGroup method is Changes all the app.Map<HttpVerb> methods to
available to help organize such todoItems.Map<HttpVerb>.
groups.
It reduces repetitive code and
Removes the URL prefix /todoitems from the
allows for customizing entire Map<HttpVerb> method calls.
groups of endpoints with a
single call to methods Test the endpoints to verify that they work the
like RequireAuthorization and same.
WithMetadata.
USE THE TYPEDRESULTS API
Returning TypedResults rather than
Results has several advantages,
including testability and automatically
returning the response type metadata
for OpenAPI to describe the
endpoint. For more information, see
TypedResults vs Results.
The Map<HttpVerb> methods can
call route handler methods instead of
using lambdas
USE THE TYPEDRESULTS API
Returning TypedResults rather than
Results has several advantages,
including testability and automatically
returning the response type metadata
for OpenAPI to describe the
endpoint. For more information, see
TypedResults vs Results.
The Map<HttpVerb> methods can
call route handler methods instead of
using lambdas
CREATE A NEW PROJECT FOR THE CLIENT
Create a new project for the client, such as a
Console Application.
Install-Package
Microsoft.AspNet.WebApi.Client
CREATE A NEW PROJECT FOR THE CLIENT
RESULTS FROM THE CLIENT
PRACTICE
Get Customer object by CustomerID
Get List of Customers
Check Exist Order by CustomerID
Get List of Orders
AUTHENTICATION
RUN AND TEST - GET DATA
ADD AUTHENTICATION
dotnet add package
To add authentication to your Microsoft.AspNetCore.Authentication.JwtBearer
minimal Web API project in
ASP.NET Core, you can follow
these steps:
1. Add the required authentication
dependencies:
First, you need to add the
necessary authentication-related
packages to your project. You can
do this by adding the following
NuGet packages:
ADD AUTHENTICATION
ADD AUTHENTICATION
{ "Authentication": {
"DefaultScheme": "LocalAuthIssuer",
"Schemes": { "Bearer": {
"ValidAudiences": [
"https://localhost:7259",
"http://localhost:5259" ],
"ValidIssuer": "dotnet-user-jwts" },
"LocalAuthIssuer": {
"ValidAudiences": [
"https://localhost:7259",
"http://localhost:5259" ],
"ValidIssuer": "local-auth" } } } }
ADD AUTHENTICATION
ADD AUTHENTICATION
ADD AUTHENTICATION – WRONG REQUIRE