API Development Using ASP Net Core Web API
API Development Using ASP Net Core Web API
API Development
Using ASP.NET
Core Web API
Practical approach for developing the
API in asp.net core
By
Sardar Mudassar Ali Khan
Senior Software Engineer
Scientific Researcher
Blogger at C# Corner
2
AUTHOR NOTE
I welcome you all in API Development using Asp.Net Core Web API the topic discussed in this
book based on practical knowledge of the industry. In this book we will study the complete projects
and discuss the project from start to end we will apply all the software Development principles,
Design Architecture and Design Patterns, and Generics that are very beneficial for the
development of software products. We will architect a complete application from start to end using
Different Software Architectures.
This book is the property of the Author and copying any kind of Content is a criminal offense
so if you see any mistake in this book then contact us at the official email address
[email protected] or the official email address of Author
[email protected].
Every step taken to word the completion of this book is based on an expert review of
industry experts.
3
DEDICATION
Every single step that was taken towards the completion of the book was because of the strong
background provided by my parents they supported me morally. Moreover, the community of C#
Corner helped me a lot in getting knowledge and solution where I was stuck. They motivate me
in every situation and always ask to us never give up everything possible in the world. They held
our hands firmly never letting us get down and made it possible for us to get through. This book
is also dedicated to my seniors who motivated us to guide us in this regard.
The pure dedication of my book is to my parents our soul parents- the teacher and friends.
Teachers always motivated and boosted us with full support whenever required.
4
DECLARATION
I Sardar Mudassar Ali hereby declare that this book contains original work and that not any part
of it has been copied from any other sources. It is further declaring that I have completed my book
under the project of Free Education for Humanity and with the guidance of my teachers and my
senior colleagues and this is entirely possible based on my efforts and, my ideas.
5
ACKNOWLEDGEMENT
It would be my pleasure and I am feeling ecstatically rapturous to pay the heartiest thanks. First,
To Allah (SWT) who is most beneficent and most merciful that he enabled me and blessed me to
take the pebble out of his multitude of bounties. To my dear parents, their prayers become true
towards the completion of my book. I am greatly beholden to my esteemed honorable motivator
and kind-hearted, teachers, friends, and colleagues who supported my idea all the way and never
let me down and corporate with me in this way completely sincerely and heartedly.
Also, special thanks to those who helped me a lot in my way, but I have forgotten them to mention
here.
6
PREFACE
API Development in asp.net core web API in this book we adopted a practical approach
for the development of software products. This book is divided into four parts every part
has its dimension. In this book, we will explain the fully featured projects and how we can
architect the application using the following architectures.
7
PART 5: API Testing Using Postman.
1) Introduction
2) API Testing Using Postman in Asp.net Core
3) Test POST, PUT, DELETE, GET, UPDATE Endpoints Using Postman
4) Conclusion
8
PUBLISHER
CSharp Corner
https://www.c-sharpcorner.com/
9
Contents
What is REST ARCHITECTURE? .............................................................................. 11
API Development in Asp.Net Core Using Three Tier Architecture ........................ 39
API Development in Asp.Net Core Using Onion Architecture ............................... 59
API Testing Using Postman ...................................................................................... 93
API Testing Using Swagger .................................................................................... 105
Application Deployment on Microsoft Azure Cloud ............................................. 117
Select the Net Working Options ............................................................................. 123
Application Deployment on Server ........................................................................ 135
10
1
What is REST
ARCHITECTURE?
Overview
• What is RESTful Web Service?
• RESTful Web Service Features
• RESTful Web Service Methods
• Why RESTful Web Service
• RESTful Architecture
• RESTful Principals and Constraints
• RESTful Client-Server
• Layered System
• RESTful Web Services Interfaces
• Create your first RESTful Web service in Asp.net Core Web
API
• Data Access Layer
• Business Access Layer
• Presentation Layer
Restful web services are a lightweight maintainable and scalable service that is built on the REST
Architecture. Restful Web service exposes API from your application in a secure uniform stateless
manner to the calling client can perform predefined operations using the restful service the
protocols for the REST is HTTP and Rest is a Representational State Transfer. Representational
state transfer (REST) is a de-facto standard for a software Architecture or Interactive applications
that use Web Service a Web Service that follows this standard is called RESTful such web must
provide its web resources in a textual representation and allow them to be read and modified with
stateless protocol and predefined set of operations this standard allow interoperability between
a Machine and the Internet that provide these services. REST Architecture is alternative to SOAP
and SOAP Architecture is the way to access a Web Service.
Rest Web services have come a long way since their inception. In 2002 the Web Consortium had
released the definition of WSDL and SOAP Web services and this formed the standard of how
web services are implemented in 2004 the web consortium also released the definition of an
additional standard called RESTful in past four to five years this standard has become more
popular and being used in many giants like Facebook and Twitter Microsoft. REST is a way to
access resources that lie in an articular environment you could have a server that could be hosting
important documents or pictures or videos. All these are an example of the resources if a client
says a web browser needs any of these resources it must send a request to the server to access
the resources.
The first key feature is the resource itself. Let us assume that a web application on the server
has a record of Persons if we want to access the records of the Persons by Id the details are in
the given below figure the coding part is also given.
This describes what you want to do with the resources a browser issues a GET verb to instruct the
endpoints it wants to get the data like POST is used to send the data by hitting the endpoints in
the postman or swagger and PUT is used to update the data and DELETE is used to either soft
delete the record or on permanent bases.
Request Body
Data is sent with the requested data is normally sent in the request when a POST request
is made to the REST web service in a POST call the client tells the rest web Service that
it wants to add a resource to the server hence the request body would have the details
of the resources which is required to be added to the server. As shown in the figure
below.
Response Body
This is the main body of the response so in our RESTful API Example if we were to query the
web service via the GET Request, we server returns the response in the JSON format which
gives us the details of Persons according to the Person ID.
Code Response
1 100 - 199 Informational Response
2 200 - 299 Successful Response
3 300 - 399 Redirects
4 400 - 499 Client Error
5 500 - 599 Server Error
• POST is used to post the data from the webserver to the database using the RESTful
Web Service.
• Heterogeneous language and environment this is one of the fundamental reasons which
is same as we have seen for SOAP as well
• It enables web applications that are built on various programming languages to
communicate with each other.
• RESTful web architecture helps the web applications to reside in different environments
some could be on windows and others could be on Linux.
• RESTful web service offers this flexibility to applications built on various programming
languages and platforms to talk to each other.
RESTful Architecture
An Application OR Architecture considered RESTful or Rest Style has the following
Characteristics
• A-State and functionality are divided into distributed resources which means that every
resource should be accessible via the normal HTTP Commands like getting, POST,
PUT, DELETE, if someone wanted to get a file from a server, they should be able to issue
the GET request and get the file. If we want to put the file on the server, we will use
either POST or PUT request, and finally, if we want to delete the file from the storage,
we must use a DELETE request.
• The architecture is client/server stateless layered and supports the caching.
• The client-server is the typical architecture where the server can be web server hosting
the application and the client can be as simple as the web browsers.
• Stateless means that the state of the application is not maintained in REST
If we want to delete a resource from a server using the DELETE Command, you cannot pass the
deleted information to the next request. To ensure that the resources are deleted you would need
to issue the GET request first to get all the information from the server after which one would
need to see if the resource were deleted.
CLENT SERVER
Stateless
The concept of stateless means that it is up to the client to ensure that all the required information
is provided to the server. This is required so that server can process the response appropriately
the server should not maintain any soft of the information between requests from the client
requests the server and the server give the response to the client appropriately.
Cache
The Cache concept is to help with the problem of stateless which was described in the
last point since each client request is independent sometimes the client might ask the
server for the same request again even though it had already asked for it in the past. This
is even though it had already asked for it in the past. This request will go to the server and
the server will give a response. This increase the traffic across the network the cache is
the concept implemented on the client to store requests which have already been sent to
the server so if the same request is given by the client instead of going to the server this
saves the amount of to and fro network traffic from the client to the server.
Layered System
The concept of a layered system is that any additional layer such as a middleware layer can be
inserted between the client and the actual server hosting the RESTful web service the
middleware layer is where all the business logic is created this can be an extra service created
• POST is used to post the data from a web server to the database using the RESTful
Web Service.
• GET is used to get the list of all records from the database either all records or based
on specific I would like Person ID or employed.
• DELETE is used to delete all the records from the database or based on a specific Id.
• PUT is used to Replace the record or update a record based on a Specific Id.
• PATCH method provides an entity containing the list of changes to be applied to the
resources requesting using the HTTP Request-URI.
• OPTIONS The options method represents a request for information about the
communication options available on the request/response chain identified by Request-
URI.
• TRACE The trace method performs a message look back test along the path to the
target resources providing a useful debugging mechanism.
All the Data in Data Access Layer and All the Crud Operations are in Data Access Layer for
Business Logic we have Business Access layer in which we will do our All Operations Related to
our Business.
Step 3 First, Add the Model Person in the Data Access Layer
using System;
using
System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
using
System.ComponentModel.DataAnnotations.Sch
ema; namespace DAL.Model
{
[Table("Persons", Schema =
"dbo")] public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Iden
tity)] public int Id { get; set; }
[Required]
[Display(Name = "UserName")]
public string UserName { get; set; }
[Required]
[Display(Name = "UserPassword")]
public string UserPassword { get;
set; } [Required]
[Display(Name = "UserEmail")]
public string UserEmail { get; set; }
[Required]
[Display(Name = "CreatedOn")]
public DateTime CreatedOn { get; set; } = DateTime.Now;
[Required]
[Display(Name = "IsDeleted")]
public bool IsDeleted { get; set; } = false;
}
}
Step 4 Add the Enter face for all the operation you want to perform.
namespace DAL.Interface
{
try
{
throw;
_dbContext.SaveChanges();
Step 6
Add the Data Folder and then add the Db Context Class set the database connection
using SQL Server before starting the migration check these four packages in All of Your
Project
Like
// This method gets called by the runtime. Use this method to add
services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")
));
services.AddController
s();
services.AddHttpClient
();
services.AddTransient<IRepository<Person>,RepositoryPerson>();
services.AddTransient<PersonService,PersonService>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title =
"AspNetCORE5WebAPICrud", Version = "v1" });
});
}
app.UseHttpsRedirectio
n(); app.UseRouting();
app.UseAuthorization()
;
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
{
public class ApplicationDbContext : DbContext
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Person> Persons { get; set; }
Step 7 Now start the migration Command for Creating the Table in Database.
After Executing the command, we have the migration folder in our Data Access Layer
that contain the Definition of Person Table
namespace DAL.Repository
{
public class RepositoryPerson : IRepository<Person>
{
ApplicationDbContext _dbContext;
public RepositoryPerson(ApplicationDbContext applicationDbContext)
{
_dbContext = applicationDbContext;
}
public async Task<Person> Create(Person _object)
{
var obj = await _dbContext.Persons.AddAsync(_object);
_dbContext.SaveChanges()
; return obj.Entity;
}
Step 10
Again, Modify the Start Up Class for Adding Transient to register the service business
Layer and Data Access Layers Classes.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCORE5WebAPICrud
_configuration = configuration;
// This method gets called by the runtime. Use this method to add services to
the container.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddHttpClient();
services.AddTransient<IRepository<Person>, RepositoryPerson>();
services.AddTransient<PersonService, PersonService>();
services.AddControllers();
services.AddSwaggerGen(c =>
});
// This method gets called by the runtime. Use this method to configure the
HTTP request pipeline.
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
endpoints.MapControllers();
});
namespace AspNetCORE5WebAPICrud.Controllers
{
[Route("api/[controller]")] [ApiController]
public class PersonDetailsController : ControllerBase
{
private readonly PersonService _personService; private readonly IRepository<Person>
_Person;
try
{
await _personService.AddPerson(person); return true;
}
catch (Exception)
{
return false;
}
}
//Delete Person [HttpDelete("DeletePerson")]
public bool DeletePerson([FromBody] String UserEmail)
{
try
{
catch (Exception)
{
return false;
}
}
//Delete Person [HttpPut("UpdatePerson")]
public bool UpdatePerson([FromBody] String UserEmail)
{
try
{
catch (Exception)
{
return false;
}
}
//GET All Person by Name [HttpGet("GetAllPersonByName")]
public Object GetAllPersonByName(string UserEmail)
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
return json;
}
}
}
Run the project then in the browser Swagger UI will be shown to the Tester
Step 2 Test POST End Point
50
Introduction
In this chapter, we'll look at three-tier architecture and how to incorporate the Data Access Layer
and Business Access Layer into a project, as well as how these layers interact.
Right Click on the Presentation layer and then click on add => project Reference
Now we'll add the Data Access layer project references to the Business layer.
➢ Right Click on the Business access layer and then Click Add Button => Project References
Project Structure
We use a three-tier architecture in this project, with a data access layer, a business access layer,
and an application presentation layer.
The Presentation layer is the top-most layer of the 3-tier architecture, and its major role is to
display the results to the user, or to put it another way, to present the data that we acquire from
the business access layer and offer the results to the front-end user.
The main function of this layer is to access and store the data from the database and the process
of the data to business access layer data goes to the presentation layer against user request.
➢ Add the Class Library project of Asp.net for Data Access Layer
➢ Right Click on the project and then go to the add the new project window and then add the
Asp.net Core class library project.
As you can see, our project now has a Presentation layer, Data Access Layer, and Business
Access layer.
In this Layer we have the Following Folders Add these folders to your Data access layer
• Contacts
• Data
• Migrations
• Models
• Repositories
Contacts
In the Contract Folder, we define the interface that has the following function that performs the
desired functionalities with the database like
namespace JWTTokenAuthInAspNet6_DAL.Contracts
{
public interface IRepository<T>
{
public Task<T> Create(T _object);
public void Delete(T _object);
}
}
In the Data folder, we have Db Context Class this class is very important for accessing the data
from the database.
Migrations
The Migration Folder contains information on all the migrations we performed during the
construction of this project. The Migration Folder contains information on all the migrations we
performed during the construction of this project.
Models
Our application models, which contain domain-specific data, and business logic models, which
represent the structure of the data as public attributes, business logic, and methods, are stored in
the Model folder.
namespace JWTTokenAuthInAspNet6_DAL.Models
{
public class AppUser: IdentityUser
{
public int Id { get; set; }
public string? Name { get; set; }
public string? AccountType { get; set; }
public string? PhoneNo { get; set; }
public string? Password { get; set; }
public string? ShopName { get; set; }
public string? BusinessType { get; set; }
public string? UserRole { get; set; }
public bool? IsDeleted { get; set; }
}
}
Repository
using JWTTokenAuthInAspNet6_DAL.Contracts;
using JWTTokenAuthInAspNet6_DAL.Data;
using JWTTokenAuthInAspNet6_DAL.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JWTTokenAuthInAspNet6_DAL.Repositories
{
public class RepositoryAppUser : IRepository<AppUser>
{
private readonly AppDbContext _appDbContext;
private readonly ILogger _logger;
Our Structure of the project in the Business Access Layer will be like this.
Services
Services define the application's business logic. We develop services that interact with the data
layer and move data from the data layer to the presentation layer and from the presentation layer
to the data access layer.
Example
using JWTTokenAuthInAspNet6_DAL.Contracts;
using JWTTokenAuthInAspNet6_DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JWTTokenAuthInAspNet6_BAL.Services
{
public class ServiceAppUser
{
public readonly IRepository<AppUser> _repository;
public ServiceAppUser(IRepository<AppUser> repository)
{
_repository = repository;
}
//Create Method
public async Task<AppUser> AddUser(AppUser appUser)
{
try
{
if (appUser == null)
{
throw new ArgumentNullException(nameof(appUser));
}
else
{
return await _repository.Create(appUser);
}
}
catch (Exception)
throw;
}
}
{
try
{
if (Id != 0)
{
var obj = _repository.GetAll().Where(x => x.Id == Id).FirstOrDefault();
_repository.Delete(obj);
}
}
catch (Exception)
{
throw;
}
}
{
try
{
if (Id != 0)
{
var obj = _repository.GetAll().Where(x => x.Id == Id).FirstOrDefault();
if (obj != null)
_repository.Update(obj);
}
}
catch (Exception)
{
throw;
}
throw;
}
}
}
}
Presentation layer
The top-most layer of the 3-Tier architecture is the Presentation layer the main function of this
layer is to give the results to the user or in simple words to present the data that we get from the
business access layer and give the results to the front-end user.
In the presentation layer, we have the default template of the asp.net core application here OUR
structure of the application will be like this.
Conclusion
In this chapter, we have learned about 3-tier Architecture and how the three-layer exchange data
between them how we can add the Data Access Layer and Business access layer in the project
and studied how these layers communicate with each other.
The top-most layer of the 3-Tier architecture is the Presentation layer the main function of this
layer is to give the results to the user or in simple words to present the data that we get from the
business access layer and give the results to the front-end user.
The main function of this application is to access and store the data from the database and the
process of the data to business access layer data goes to the presentation layer against user
request.
70
Introduction
In this chapter, we will cover the onion architecture using the Asp.Net 6 Web API. Onion
architecture term introduces by Jeffrey Palermo in 2008 this architecture provides us a better
way to build applications using this architecture our applications are better testable
maintainable and dependable on infrastructures like databases and services. Onion
architecture solves common problems like coupling and separation of concerns.
Domain Layer
Repository Layer
The repository layer act as a middle layer between the service layer and model objects we will
maintain all the database migrations and database context Object in this layer. We will add
the interfaces that consist the of data access pattern for reading and writing operations with
the database.
Service Layer
This layer is used to communicate with the presentation and repository layer. The service layer
holds all the business logic of the entity. In this layer services interfaces are kept separate
from their implementation for loose coupling and separation of concerns.
Presentation Layer
In the case of the API Presentation layer that presents us the object data from the database
using the HTTP request in the form of JSON Object. But in the case of front-end applications,
we present the data using the UI by consuming the APIS.
Project Structure.
Domain Layer
This layer lies in the center of the architecture where we have application entities which are
the application model classes or database model classes using the code first approach in the
application development using Asp.net core these entities are used to create the tables in the
database.
For the Domain layer, we need to add the library project to our application.
First, you need to add the Models folder that will be used to create the database entities. In
the Models folder, we will create the following database entities.
Base Entity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Models
{
public class BaseEntity
{
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public bool IsActive { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Models
{
public class Departments :BaseEntity
{
public int Id { get; set; }
public string DepartmentName { get; set; }
public int StudentId { get; set; }
public Student Students { get; set; }
}
}
Result
Result Entity will extend the base entity
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Models
{
public class Resultss : BaseEntity
{
[Key]
public int Id { get; set; }
public string? ResultStatus { get; set; }
public int StudentId { get; set; }
public Student Students { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Models
{
public class Student : BaseEntity
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public string? Address { get; set; }
public string? Emial { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? Country { get; set; }
public int? Age { get; set; }
public DateTime? BirthDate { get; set;}
}
}
SubjectGpa
Subject GPA Entity will extend the Base Entity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Models
{
public class SubjectGpas : BaseEntity
{
public int Id { get; set; }
public string SubjectName { get; set; }
Data Folder
Add the Data in the domain that is used to add the database context class. The database
context class is used to maintain the session with the underlying database using which you
can perform the CRUD operation.
using DomainLayer.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DomainLayer.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Student> Students { get; set; }
public DbSet<Departments> Departments { get; set; }
public DbSet<SubjectGpas> SubjectGpas { get; set; }
public DbSet<Resultss> Results { get; set; }
}
}
add-migration OnionArchitectureV1
After executing the commands now, you need to update the database by executing the
update-database Command
Migration Folder
After executing both commands now you can see the migration folder in the domain layer.
Now we will work on Repository Layer we will follow the same project as we did for the Domain
layer add the library project in your applicant and give a name to that project Repository layer.
But here we need to add the project reference of the Domain layer in the repository
layer. Write click on the project and then click the Add button after that we will add the
project references in the Repository layer.
• I Repository
• Repository
Generic Interface will extend the Base-Entity for using some properties. The Code of the
generic interface is given below.
using DomainLayer.Models;
namespace RepositoryLayer.IRepository
{
public interface IRepository<T> where T: BaseEntity
{
IEnumerable<T> GetAll();
T Get(int Id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
void Remove(T entity);
void SaveChanges();
}
}
Repository
Now we create the Generic repository that extends the Generic IRepository Interface. The
Code of the generic repository is given below.
using DomainLayer.Data;
using DomainLayer.Models;
using Microsoft.EntityFrameworkCore;
using RepositoryLayer.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RepositoryLayer.Repository
{
public class Repository<T> : IRepository<T> where T : BaseEntity
{
#region property
private readonly ApplicationDbContext _applicationDbContext;
#region Constructor
public Repository(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
entities = _applicationDbContext.Set<T>();
}
#endregion
}
}
Service Layer
This layer is used to communicate with the presentation and repository layer. The service layer
holds all the business logic of the entity. In this layer services interfaces are kept separate
from their implementation for loose coupling and separation of concerns.
Now we need to add a new project to our solution that will be the service layer we will follow
the same process for adding the library project in our application but here we need some extra
work after adding the project we need to add the reference of the Repository Layer.
• ICustomServices
• CustomServices
Now in the ICustomServices folder, we will create the ICustomServices Interface this interface
holds the signature of the method we will implement these methods in the customs service
code of the ICustomServices Interface given below.
using DomainLayer.Models;
using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace ServiceLayer.ICustomServices
{
public interface ICustomService<T> where T : class
{
IEnumerable<T> GetAll();
T Get(int Id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
void Remove(T entity);
}
}
Custom Service
In the custom service folder, we will create the custom service class that inherits the
ICustomService interface code of the custom service class given below. We will write the crud
for our all entities.
For every service, we will write the CRUD operation using our generic repository.
Department Service
Student Service
using DomainLayer.Models;
using RepositoryLayer.IRepository;
using ServiceLayer.ICustomServices;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ServiceLayer.CustomServices
{
public class StudentService : ICustomService<Student>
{
private readonly IRepository<Student> _studentRepository;
public StudentService(IRepository<Student> studentRepository)
{
_studentRepository = studentRepository;
}
public void Delete(Student entity)
{
try
{
if(entity!=null)
{
_studentRepository.Delete(entity);
_studentRepository.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
throw;
}
}
throw;
}
}
throw;
}
}
public void Update(Student entity)
{
try
{
if(entity!=null)
{
_studentRepository.Update(entity);
_studentRepository.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
}
}
Result Service
namespace ServiceLayer.CustomServices
{
public class ResultService : ICustomService<Resultss>
{
private readonly IRepository<Resultss> _studentRepository;
public ResultService(IRepository<Resultss> studentRepository)
{
_studentRepository = studentRepository;
}
public void Delete(Resultss entity)
{
try
{
if (entity != null)
{
_studentRepository.Delete(entity);
_studentRepository.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
}
catch (Exception)
{
throw;
}
}
throw;
}
}
throw;
}
}
throw;
}
}
public void Update(Resultss entity)
{
try
{
if (entity != null)
{
_studentRepository.Update(entity);
_studentRepository.SaveChanges();
}
}
catch (Exception)
{
throw;
}
using DomainLayer.Models;
using RepositoryLayer.IRepository;
using ServiceLayer.ICustomServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceLayer.CustomServices
{
public class SubjectGpasService : ICustomService<SubjectGpas>
{
private readonly IRepository<SubjectGpas> _studentRepository;
public SubjectGpasService(IRepository<SubjectGpas> studentRepository)
{
_studentRepository = studentRepository;
}
public void Delete(SubjectGpas entity)
{
try
{
if (entity != null)
{
_studentRepository.Delete(entity);
_studentRepository.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
}
catch (Exception)
{
throw;
}
}
throw;
}
}
throw;
}
}
throw;
}
}
public void Update(SubjectGpas entity)
{
try
{
if (entity != null)
{
_studentRepository.Update(entity);
_studentRepository.SaveChanges();
}
throw;
}
}
}
}
Presentation Layer
The presentation layer is our final layer that presents the data to the front-end user on every
HTTP request.
In the case of the API presentation layer that presents us the object data from the database
using the HTTP request in the form of JSON Object. But in the case of front-end applications,
we present the data using the UI by consuming the APIS.
The presentation layer is the default Asp.net core web API project Now we need to add the
project references of all the layers as we did before
Dependency Injection
Now we need to add the dependency Injection of our all services in the program.cs class
using DomainLayer.Data;
using DomainLayer.Models;
using Microsoft.EntityFrameworkCore;
using RepositoryLayer.IRepository;
using RepositoryLayer.Repository;
using ServiceLayer.CustomServices;
using ServiceLayer.ICustomServices;
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Controllers
Controllers are used to handle the HTTP request. Now we need to add the student controller
that will interact will our service layer and display the data to the users.
using DomainLayer.Data;
using DomainLayer.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RepositoryLayer.IRepository;
using ServiceLayer.ICustomServices;
namespace OnionArchitectureInAspNetCore6WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly ICustomService<Student> _customService;
private readonly ApplicationDbContext _applicationDbContext;
public StudentsController(ICustomService<Student> customService,
ApplicationDbContext applicationDbContext)
{
_customService = customService;
_applicationDbContext = applicationDbContext;
}
[HttpGet(nameof(GetStudentById))]
}
[HttpDelete(nameof(DeleteStudent))]
public IActionResult DeleteStudent(Student student)
{
if(student!=null)
{
_customService.Delete(student);
return Ok("Deleted Successfully");
}
else
{
return BadRequest("Something went wrong");
}
}
}
}
Output
Now we will run the project and will see the output using the swagger.
Overview
• Introduction
• How to Test API Web Service in Asp Net Core 5 Using Postman
• Test Post Call in Postman
• Test Get Call in Postman
• Test Put Call in Postman
• Test Delete Call in Postman
• Conclusion
How to Test API Web Service in Asp Net Core 5 Using Postman
In Postman for API Testing the professional approach is make the collection for API Requests
for collecting the responses like GET PUT POST AND DELETE Request Response. Open the
post man Click on Create Collection.
Now the collection is ready for collecting the API Request Response.
We are going to test the following use case for this article. In this article I am going to test the
POST, GET, PUT, DELETE, AND UPDATE, Endpoints of Web Service.
Here in this example we are going to test the Web Servive using Postman Developed using
the Asp.Net Core 5 Web API
{
"id": 0,
"userName": "string",
"userPassword": "string",
"userEmail": "string",
"createdOn": "2021-04-16T20:38:41.062Z",
"isDeleted": true
}
If we want to Create the New Person in the Database, we must send the JSON Object to the
End Point then data is posted by Postman UI to POST End Point in the Controller Then Create
Person Object Creates the Complete Person Object in the Database.
In Deletion of the record just select body and the select the form data pass the id value the for
the record you want to delete from the database.
In Above two pictures you can see that after hitting the Delete End point our server response
is true it indicates that our record has been delete from the database against our desired Email.
Hit the GET Endpoint for getting all record from the database.
We are going to update the given below JSON Object in the database
{
"id": 0,
"userName": "Mudassar Ali Khan",
"userPassword": "17859345@",
"userEmail": "[email protected]",
"createdOn": "2021-04-16T20:41:15.443Z",
"isDeleted": false
}
To given below JSON object
{
"id": 0,
"userName": "Sardar Mudassar Ali Khan",
"userPassword": "17859345@",
"userEmail": "[email protected]",
"createdOn": "2021-04-16T20:41:15.443Z",
"isDeleted": false
}
After the successful submission of data, you can see that our server response is true it
indicates that our data has been successfully submitted in the database
Overview
• Introduction
• How to Test API Web Service in Asp Net Core 5 Using Swagger
• Test Post Call in Swagger
• Test Get Call in Swagger
• Test Put Call in Swagger
• Test Delete Call in Swagger
• Conclusion
Swagger (Open API) is a language-agnostic specification for describing and documenting the
REST API. Swagger Allows both the Machine and Developer to understand the working and
capabilities of the Machine without direct access to the source code of the project the main
objectives of swagger (Open API) are to:
How to Test API Web Service in Asp Net Core 5 Using Swagger
We are going to test the following use case for this article. In this article I am going to test
the POST, GET, PUT, DELETE, AND UPDATE, Endpoints of Web Service.
Here in this example, we are going to test the Web Service using Swagger Developed using
the Asp.Net Core 5 Web API.
1. {
2. "id": 0,
3. "userName": "string",
4. "userPassword": "string",
5. "userEmail": "string",
6. "createdOn": "2021-04-16T20:38:41.062Z",
7. "isDeleted": true
8. }
If we want to Create the New Person in the Database, we must send the JSON Object to the
End Point then data is posted by Swagger UI to POST End Point in the Controller then Create
Person Object Creates the Complete Person Object in the Database.
We are going to delete the record against the given email if the API service equal to true then
our record deleted from the database successfully.
After the successful execution of Web service, all the record is visible to us in the form of a
JSON object in database we have Only One Record so that
We are going to update the given below JSON Object in the database.
1. {
2. "id": 0,
3. "userName": "Mudassar Ali Khan",
4. "userPassword": "17859345@",
5. "userEmail": "[email protected]",
6. "createdOn": "2021-04-16T20:41:15.443Z",
7. "isDeleted": false
8. }
1. {
2. "id": 0,
3. "userName": "Sardar Mudassar Ali Khan",
4. "userPassword": "17859345@",
5. "userEmail": "[email protected]",
6. "createdOn": "2021-04-16T20:41:15.443Z",
7. "isDeleted": false
8. }
Swagger (Open API) is a language-agnostic specification for describing and documenting the
REST API. Swagger Allows both the Machine and Developer to understand the working and
capabilities of Machine without direct access to the source code of the project the main
objectives of swagger (Open API) are too,
Swagger is the Interface Description Language for Describing the RESTful APIS Expressed
using JSON. Swagger is used to gathering with a set of open-source software tools to Design
build documents and use Restful Web Services Swagger includes automated documentation
code generation and test the generation. Three main components of Swashbuckle
Swashbuckle.AspNetCore.Swagger is the Object Model and Middleware to expose swagger
Document as JSON End Points.
Overview
• Introduction
• Deployment Procedure
• Server Configuration
• Deployment Steps
• Conclusion
Note that if you create tags and then change resource settings on other tabs, your tags
will be automatically updated.
Now you can see that our deployment process succeeded and we can go to the
Created resource.
Application Status
Now You Can See that Our Application is Live on the Azure Cloud.
Now you can see that we have the option for Import Profile and we will import the
profile that we have downloaded from the Azure App Service portal. Click the Import
Profile Option.
Now you can see that visual studio get all the information about our Azure App you can see
the URL of our application.
Deployment Status
Our Publication on Azure Cloud has been done. You can see the publication status successful.
Overview
• Introduction
• Deployment Procedure
• Server Configuration
• Deployment Steps
• Conclusion
146
Introduction
In this chapter, we will learn about how to deploy the asp.net core 5 websites on a server using
visual studio 2019.
Step 2 Create the project asp.net Core 5 Web API using Visual Studio
Create the project using visual studio and select the asp.net core version .Net 5.0 Current.
Give the Name of your project that you want to develop My Project is ONP
(Online Prescription Application)
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Click the Publish option a new window will appear now select the project publication option
here you have 5 to 6 options given below.
You all get this type of option in your control panel just get the publish profile from and down
that file in your system.
After Uploading the publish profile setting file in the visual studio just click on the Finish option
and you will get given the below window.
All the information will automatically upload fetched from the uploaded publish profile and this
information will automatically save in the visual studio for future deployments.
But before the publication just checks your application should be in release mode and the
Webhost environment should be in production mode.
“Happy Coding”
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS