0% found this document useful (0 votes)
8 views49 pages

Working With ASP - NET Core Web API

The document provides an overview of ASP.NET Core Web API, detailing client-server architecture, RESTful services, and the characteristics of ASP.NET Web API. It includes demonstrations for creating an ASP.NET Core Web API application, consuming it with ASP.NET MVC Core, and using WinForms applications. Additionally, it covers HTTP verbs, status codes, and attributes used in ASP.NET Core for configuring web API behavior.

Uploaded by

Fergus Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views49 pages

Working With ASP - NET Core Web API

The document provides an overview of ASP.NET Core Web API, detailing client-server architecture, RESTful services, and the characteristics of ASP.NET Web API. It includes demonstrations for creating an ASP.NET Core Web API application, consuming it with ASP.NET MVC Core, and using WinForms applications. Additionally, it covers HTTP verbs, status codes, and attributes used in ASP.NET Core for configuring web API behavior.

Uploaded by

Fergus Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Working with ASP.

NET Core Web API


Objectives

Overview Client-server Architecture

Overview ASP.NET Core RESTful Services

Explain about Web Service

Explain about ASP.NET Web API Characteristics

Demo create ASP.NET Core Web API application

Demo create ASP.NET MVC Core Application consume Web API

Demo create WinForms Application consume Web API
07/23/2025 2
Client-server Architecture

Client-server architecture is a computing model in which the server hosts,
delivers and manages most of the resources and services to be consumed by
the client

This type of architecture has one or more client computers connected to a
central server over a network or internet connection

Client-server architecture is also known as a networking computing model or
client-server network because all the requests and services are delivered over
a network
07/23/2025 3
Client-server Architecture
1. Client requests data from server
2. Load balancer routes the request
to the appropriate server
3. Server processes the request
client
4. Server queries appropriate
database for some data
5. Database returns the queried
data back to the server
6. The server processes the data
and sends the data back to the
client
7. This process repeats
07/23/2025 4
Web Service Acronyms

Web services are services that use the HTTP communication standard,
so they are sometimes called HTTP or RESTful services

Web services can also mean Simple Object Access Protocol (SOAP) services
that implement some of the WS-* standards

Microsoft .NET Framework 3.0 and later includes a remote procedure call
(RPC) technology named Windows Communication Foundation (WCF), which
makes it easy for developers to create services including SOAP services that
implement WS-* standards

gRPC is a modern cross-platform open source RPC framework created by
Google (the "g" in gRPC)

07/23/2025 5
RESTful Services

REST stands for representational state transfer. It is an architectural style
that defines a set of guidelines for building web services

The following is a simple diagram of a REST-based service:

07/23/2025 6
ASP.NET Core and RESTful services

ASP.NET Web API from the beginning was designed to be a service-based
framework for building RESTful (Representational State Transfer) services

ASP.NET Web API is based on the MVC framework minus the “V” (view), with
optimizations for creating headless services. These services can be called by
any technology

Calls to a Web API service are based on the core HTTP Verbs (Get, Put, Post,
Delete) through a URI (Uniform Resource Identifier)

The ASP.NET MVC framework started gaining traction almost immediately, and
Microsoft released ASP.NET Web API with ASP.NET MVC 4 and Visual Studio
2012

ASP.NET Web API 2 was released with Visual Studio 2013 and then updated
the framework to version 2.2 with Visual Studio 2013 Update 1
07/23/2025 7
ASP.NET Core and RESTful services

ASP.NET Web API is an ideal platform for building RESTful services

ASP.NET Web API is built on top of ASP.NET and supports ASP.NET
request/response pipeline

ASP.NET Web API maps HTTP verbs to method names

ASP.NET Web API supports different formats of response data. Built-in support
for JSON, XML, BSON format

ASP.NET Web API can be hosted in IIS, Kestrel, Self-hosted or other web
server that supports

ASP.NET Core Web API includes new HttpClient to communicate with Web API
server. HttpClient can be used in ASP.MVC server side, Windows Form
application, Console application or other apps
07/23/2025 8
07/23/2025 9
ASP.NET Core and RESTful services

ASP.NET Web API has been built to map the web/HTTP programming model to
the .NET Framework programming model. It uses familiar constructs, such as
Controller, Action, Filter, and so on, which are used in ASP.NET MVC

ASP.NET Web API is designed on top of the ASP.NET MVC runtime, along with
some components that simplify HTTP programming

ASP.NET Core supports creating RESTful services. To handle requests, a web
API uses controllers

A Web API consists of one or more controller classes that derive
from ControllerBase

07/23/2025 10
07/23/2025 11
ControllerBase Class

The ControllerBase class provides the core functionality for both ASP.NET Core
web applications and services, in addition to helper methods for returning
HTTP status codes and properties
 Some of the Properties provided by the ControllerBase Class:
Properties Description
HttpContext Returns the HttpContext for the currently executing action
Request Returns the HttpRequest for the currently executing action
Response Returns the HttpResponse for the currently executing action

ModelState Returns the state of the model in regard to model binding and validation
Url Returns an instance of the IUrlHelper, providing access to building URLs for ASP.NET
MVC Core applications and services
RouteData Returns the RouteData for the currently executing action
07/23/2025 12
ControllerBase Class

Some of the Helper Methods provided by the ControllerBase Class:
Method Notes

BadRequest Returns 400 status code


NotFound Returns 404 status code
PhysicalFile Returns a file
TryUpdateModelAsync Invokes model binding
TryValidateModel Invokes model validation
NoContent Creates a NoContentResult object that produces an empty Status204NoContent response
Ok Creates a OkResult object that produces an empty Status200OK response
Accepted() Creates a AcceptedResult object that produces an Status202Accepted response
Content(String) Creates a ContentResult object by specifying a content string
07/23/2025 13
Request and Response

A REST request generally consists of the following:
 HTTP verb: This denotes what kind of operation the requests want to perform on the
server

 Header: This element of the REST request allows the client to pass more information
about the request

 URL: The actual path to the resource that the REST request wants to operate on

 Body: The body can contain extra data related to a resource to identify or update it.
This is optional though
07/23/2025 14
HTTP verbs

The following are basic HTTP verbs used while requesting a REST system for
resource interaction:
 GET: Used to retrieve a specific resource by its identity or a collection of resources

 POST: Used to create/insert a new resource

 PUT: Used to update a specific resource by its identity

 DELETE: Used to remove a specific resource by its identity

07/23/2025 15
Status Code

When a server returns responses, it includes status codes. These status
codes inform the client how the request performed on the server
Status Code Explanation
200 OK Standard response for successful HTTP requests
201 CREATED Standard response for an HTTP request when an item is successfully
NO CONTENT Standard response for successful HTTP requests, if nothing is returned in
204
the response body
Request cannot be processed because of bad request syntax, excessive size, or another
400 BAD REQUEST
client error
403 FORBIDDEN Client does not have permission to access the requested resource

404 NOT FOUND Resource could not be found at this time. It might have been deleted, or does not exist yet
500 INTERNAL This response comes whenever there is a failure or exception happens while processing
SERVER ERROR the server side codes
07/23/2025 16
A web API sample

Create Web API by dotnet CLI


Open SampleWebAPI
project by Visual Studio

07/23/2025 17
A web API sample

Update code for WeatherForecastController.cs as follows:

07/23/2025 18
A web API sample

Run project to test Get method by Swagger

1 2

07/23/2025 19
3

07/23/2025 20
ASP.NET Core attributes

The Microsoft.AspNetCore.Mvc namespace provides attributes that can be
used to configure the behavior of web API controllers and action methods

The following example uses attributes to specify the supported HTTP action
verb and any known HTTP status codes that could be returned:
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Product> Create(Product product)
{
//………
return CreatedAtAction(nameof(GetById), new { id = product.Id },
product);
} 07/23/2025 21
ASP.NET Core attributes

Some more examples of attributes that are available:
Method Notes
HttpPost Attribute Identifies an action that supports the HTTP POST method
HttpPut Attribute Identifies an action that supports the HTTP PUT method
HttpDelete Attribute Identifies an action that supports the HTTP DELETE method
HttpGet Attribute Identifies an action that supports the HTTP GET method
Route Attribute Specifies an attribute route on a controller
HttpHead Attribute Identifies an action that supports the HTTP HEAD method
HttpOptions Attribute Identifies an action that supports the HTTP OPTIONS method
HttpPatch Attribute Identifies an action that supports the HTTP PATCH method

More attributes: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc?view=aspnetcore-5.0

07/23/2025 22
[ApiController]
[HttpGet("{id}")]
[Route("api/products")]
public ActionResult<Product> GetProduct(int id) {
public class ProductsController : ControllerBase {
// Lấ y thông tin sản phẩm từ cơ sở dữ liệu
[HttpGet("{id}")]
Product product = _productRepository.GetProduct(id);
public ActionResult<Product> GetProduct(int id) {
// Trả vềthông tin sản phẩ m return product;
// Lấy thông tin sản phẩm từ cơ sở dữ liệu dựa
}
trên id
[HttpHead("{id}")]
Product product =
public IActionResult GetProductHead(int id) {
_productRepository.GetProductById(id);
// Kiể m tra xem sản phẩm có tồn tại không
if (product == null) {
if (!_productRepository.ProductExists(id)) {
return NotFound();
return NotFound();
}
}
return Ok(product);
// Trả vềtiêu đềcủa sản phẩ m
}
Response.Headers.Add("Product-Name",
}
_productRepository.GetProductName(id));
Response.Headers.Add("Product-Price",
[HttpPatch("{id}")]
_productRepository.GetProductPrice(id).ToString());
public IActionResult UpdateUser(int id, [FromBody]
return Ok();
JsonPatchDocument<User> patchDocument) {
}
// Lấy thông tin người dùng từ cơ sở dữ liệu
User user = _userRepository.GetUserById(id);
HttpOptions("{id}")]
if (user == null) {
ublic IActionResult GetProductOptions(int id) {
return NotFound();
// Kiể m tra xem sản phẩm có tồ
n tại không
}
if (!_productRepository.ProductExists(id)) {
// Áp dụng các thay đổi từ thân yêu cầu vào đố i
return NotFound();
tượng người dùng
}
patchDocument.ApplyTo(user);
// Thiế t lập các tiêu đềhỗtrợ cho sản phẩ m
// Cập nhật thông tin người dùng trong cơ sở dữ
Response.Headers.Add("Allow", "GET, PUT, DELETE");
liệu
Response.Headers.Add("Access-Control-Allow-Origin", "*");
_userRepository.UpdateUser(user);
return Ok();
return Ok(user);
07/23/2025 23
}
ASP.NET Core attributes

07/23/2025 24
Binding Source Parameter Inference

A binding source attribute defines the location at which an action parameter's
value is found

The following binding source attributes exist:
Attribute Binding source

[FromBody] Inferred for complex types. Only one FromBody parameter can exist or an exception will
be thrown. Exceptions exist for IFormCollection and CancellationToken
[FromForm] Inferred for action parameters of type IFormFile and IFormFileCollection. When
parameter is marked with FromForm, the multipart/form-data content type is inferred
[FromHeader] Request header
[FromQuery] Inferred for any other action parameters

[FromRoute] Inferred for any parameter name that matches a route token name

[FromServices] The request service injected as an action parameter

07/23/2025 25
Binding Source Parameter Inference

07/23/2025 26
Demo 01- Create a Web API Application

07/23/2025 27
1. Open Visual Studio.NET , File | New | Project

07/23/2025 28
2. Fill out Project name: MyWebApp and Location then click Next

07/23/2025 29
3. Config as follows then click Create

4. Install the package Microsoft.EntityFrameworkCore.InMemory from Nuget


07/23/2025 30
5.Right-click on Models folder | Add | Class, named Product.cs and a class named
MyStockContext.cs then write codes as follows:

Product.cs

MyStockContext.cs

07/23/2025 31
6.Right-click on Controller folder | Add |
Controller, named ProductsController.cs

7.Open Startup.cs and update code for


ConfigureService method as follows:
//add two namespaces
using MyService.Models;
using Microsoft.EntityFrameworkCore;
//…

07/23/2025 32
8.Write codes for ProductsController.cs as follows

07/23/2025 33
9.Right-click on the project, select Open in Terminal. On
Developer PowerShell dialog, execute the following
command to run Web API project:

07/23/2025 34
10.Open the web browser and go to link to test action methods with Swagger :
http://localhost:5000/swagger/index.html

07/23/2025 35
Demo 02- Create a ASP.NET MVC Core
Application to consume Web API

07/23/2025 36
1.Create a ASP.NET MVC Core application named MyWebApp
2.Right-click on Models folder | Add | Class, named Product.cs and write codes as follows:

07/23/2025 37
3.Right-click on Controllers folder | Add | Controller named ProductManagerController.cs and write
codes as follows:

07/23/2025 38
07/23/2025 39
4.Right-click on View folder | Add | New Folder named ProductManager
5.Right-click on ProductManager folder | Add | View named Index (List) to display product list
then update codes as follows:

07/23/2025 40

Repeat this step to add views: Create as the below figure:

07/23/2025 41
6.Run MyService project (reference to Step 9 of Demo-01) then run MyWebApp project

07/23/2025 42
Demo 03- Create a Windows Forms
Application to consume Web API

07/23/2025 43
1.Create a Windows Forms application named MyWinApp
2. Install the package Microsoft.AspNet.WebApi.Client from Nuget

3. Right-click on the project add a folder named Models then add into this folder a class named
Product.cs and write codes as follows:

07/23/2025 44
4. Create a form named frmViewProducts has UI as follows:

Object Type Object name Properties / Events


Label lbProductID Text: Product ID
Label lbProductName Text: Product Name

Label lbUnitPrice Text: Unit Price


TextBox txtProductID ReadOnly: True
TextBox txtProductName
TextBox txtUnitPrice

Button btnLoad Text: Delete


Event Handler: Click

DataGridView dgvProductList ReadOnly: True


SelectionMode:FullRowSelect

Form frmViewProducts StartPosition: CenterScreen


Text: View Product List

07/23/2025 45
5. Write codes in the frmViewProducts.cs as follows and run project:

07/23/2025 46
07/23/2025 47
Lab and Assigment

1. Do Hands-on Lab:

Lab_03_AutomobileManagement_Using_ASP.NET MVC and EF Core.pdf

2. Do Assigment:

Assignment_03_eStoreManagement.pdf

07/23/2025 48
Summary

Concepts were introduced:
 Overview Client-server Architecture
 Overview ASP.NET Core and RESTful Services
 Explain about Web Service
 Explain about ASP.NET Web API Characteristics
 Demo create ASP.NET Core Web API application
 Demo create ASP.NET MVC Core Application consume Web API
 Demo create WinForms Application consume Web API

49

You might also like