0% found this document useful (0 votes)
16 views34 pages

ASP.NET Core API: Controller vs Minimal

Uploaded by

Linh Phạm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views34 pages

ASP.NET Core API: Controller vs Minimal

Uploaded by

Linh Phạm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NATIONAL ECONOMICS UNIVERSITY

SCHOOL OF INFORMATION TECHNOLOGY AND DIGITAL ECONOMICS

CHAPTER IV
[Link] CORE API - Controller based

PHAM THAO
OUTLINE

 SETUP [Link] AND WEB DEVELOPMENT


 CREATE A NEW PROJECT
 [Link] Core Web API – Minimal API
 POST
 GET
 PUT
 DELETE
 MapGroupAPI
 Use TypedResults API
 Prevent over-posting
 Call from Client
 [Link] Core Web API – Controller based
CREATE A NEW PROJECT
 [Link] is a popular web-development framework
for building web apps on the .NET platform.
 [Link] Core is the open-source version of [Link],
that runs on macOS, Linux, and Windows. [Link]
Core was first released in 2016 and is a re-design of
earlier Windows-only versions of [Link].
 [Link] 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 [Link] 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.
 [Link] Core provides various support lifecycle options to meet
the needs of your app.

[Link]
CREATE A NEW PROJECT
 [Link] 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.
[Link] 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
[Link] Core.
 Controller-based APIs
[Link] 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
[Link] Core.
 Controller-based APIs
[Link] CORE WEB API – MINIMAL API
[Link] CORE WEB API – MINIMAL API
 Add NuGet packages
 [Link]
 [Link]
THE MODEL AND DATABASE CONTEXT CLASSES

 In the project folder, create a


file named [Link] 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 = [Link](args);


highlighted code adds  [Link]<TodoDb>(opt =>
the database context [Link]("TodoList"));
to the dependency
injection  [Link]
(DI) container and Filter();
enables displaying  var app = [Link]();
database-related
exceptions:
The following code in [Link] creates an HTTP POST endpoint /todoitems that adds data to the in-memory database:

ADD THE API CODE

 The following code in  [Link]("/todoitems", async (Todo todo, TodoDb


[Link] creates an db) => { [Link](todo); await
HTTP POST endpoint [Link]();
/todoitems that adds
data to the in-  return [Link]($"/todoitems/{[Link]}",
memory database: todo); });
 Run the app. The
browser displays a
404 error because
there is no longer a /
endpoint.
The following code in [Link] creates an HTTP POST endpoint /todoitems that adds data to the in-memory database:

ADD THE API CODE

 The following code in  [Link]("/todoitems", async (TodoDb db) =>


[Link] creates an await [Link]());
HTTP POST endpoint [Link]("/todoitems/complete", async (TodoDb
/todoitems that adds db) => await [Link](t =>
data to the in-
[Link]).ToListAsync());
memory database:
[Link]("/todoitems/{id}", async (int id, TodoDb
 Run the app. The db) => await [Link](id) is Todo todo ?
browser displays a [Link](todo) : [Link]());
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)

 [Link]("/todoitems/{id}", async (int id, Todo  Update the to-do item


inputTodo, TodoDb db) => { var todo = await that has Id = 1 and set
[Link](id); its name to "feed fish":
 if (todo is null) return [Link]();
 [Link] = [Link];  { "id": 1, "name": "feed
 [Link] = [Link];
fish", "isComplete":
false }
 await [Link]();
 return [Link](); });
DELETE

 [Link]("/todoitems/{id}", async (int id,  Use Postman to delete a to-


TodoDb db) =>
do item:
 {
 if (await [Link](id) is Todo  Set the method to DELETE.
todo)
 {
 Set the URI of the object to
 [Link](todo);
delete (for example
[Link]
 await [Link]();
ems/1).
 return [Link]();
 }  Select Send.
 return [Link]();
 });
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
[Link]("/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 [Link]<HttpVerb> methods to
available to help organize such [Link]<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
[Link]
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 [Link]
minimal Web API project in
[Link] 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": [
"[Link]
"[Link] ],
"ValidIssuer": "dotnet-user-jwts" },
"LocalAuthIssuer": {
"ValidAudiences": [
"[Link]
"[Link] ],
"ValidIssuer": "local-auth" } } } }
ADD AUTHENTICATION
ADD AUTHENTICATION
ADD AUTHENTICATION – WRONG REQUIRE

You might also like