Introduction

API Web Service API is the application programming interface either for the web servers or web browsers it is the website development concept usually used in API-based website architecture for creating Web Applications like microservices. In the Given Below article, I will discuss the complete procedure of creating of API Web Service using Asp.net Core 5 and then we will see the output of the API Based Web Service. After this Process, we will Test All the Endpoints of Webservice using Swagger for POST GET DELETE AND PUT Requests.

Create your first RESTful Web service in Asp.net Core Web API

Step 1
First, create the Asp.net Core Web API in Visual Studio.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 2
Add the new project in your solution like Asp.net Core class library for Business Access Layer and Data Access Layer.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
After Adding the BAL (Business Access Layer) And DAL (Data Access Layer)
All the data in Data Access Layer and all the CRUD operations are in Data Access Layer for Business logic we have a Business Access layer in which we will do our All operations related to our business.

Data Access Layer

Given below picture is the structure of our project according to our Initial steps.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 3
First, Add the Model Person in the Data Access Layer
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code is Given Below,
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. namespace DAL.Model
  7. {
  8. [Table("Persons", Schema = "dbo")]
  9. public class Person
  10. {
  11. [Key]
  12. [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  13. public int Id { get; set; }
  14. [Required]
  15. [Display(Name = "UserName")]
  16. public string UserName { get; set; }
  17. [Required]
  18. [Display(Name = "UserPassword")]
  19. public string UserPassword { get; set; }
  20. [Required]
  21. [Display(Name = "UserEmail")]
  22. public string UserEmail { get; set; }
  23. [Required]
  24. [Display(Name = "CreatedOn")]
  25. public DateTime CreatedOn { get; set; } = DateTime.Now;
  26. [Required]
  27. [Display(Name = "IsDeleted")]
  28. public bool IsDeleted { get; set; } = false;
  29. }
  30. }
Step 4
Add the Interface for all the operation you want to perform.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code is Giver Below,
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. namespace DAL.Interface
  6. {
  7. public interface IRepository<T>
  8. {
  9. public Task<T> Create(T _object);
  10. public void Update(T _object);
  11. public IEnumerable<T> GetAll();
  12. public T GetById(int Id);
  13. public void Delete(T _object);
  14. }
  15. }
Step 5
Apply the repository pattern in your project add the class repository person
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code is Given Below,
  1. using DAL.Data;
  2. using DAL.Interface;
  3. using DAL.Model;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace DAL.Repository
  10. {
  11. public class RepositoryPerson : IRepository<Person>
  12. {
  13. ApplicationDbContext _dbContext;
  14. public RepositoryPerson(ApplicationDbContext applicationDbContext)
  15. {
  16. _dbContext = applicationDbContext;
  17. }
  18. public async Task<Person> Create(Person _object)
  19. {
  20. var obj = await _dbContext.Persons.AddAsync(_object);
  21. _dbContext.SaveChanges();
  22. return obj.Entity;
  23. }
  24. public void Delete(Person _object)
  25. {
  26. _dbContext.Remove(_object);
  27. _dbContext.SaveChanges();
  28. }
  29. public IEnumerable<Person> GetAll()
  30. {
  31. try
  32. {
  33. return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();
  34. }
  35. catch (Exception ee)
  36. {
  37. throw;
  38. }
  39. }
  40. public Person GetById(int Id)
  41. {
  42. return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
  43. }
  44. public void Update(Person _object)
  45. {
  46. _dbContext.Persons.Update(_object);
  47. _dbContext.SaveChanges();
  48. }
  49. }
  50. }
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.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Then add the project references in all of the Project Directory in API project and BAL Project
Like
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Now Modify the start-up class in project solution.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code of the start-up file is given below.
  1. using BAL.Service;
  2. using DAL.Data;
  3. using DAL.Interface;
  4. using DAL.Model;
  5. using DAL.Repository;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.HttpsPolicy;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.EntityFrameworkCore;
  11. using Microsoft.Extensions.Configuration;
  12. using Microsoft.Extensions.DependencyInjection;
  13. using Microsoft.Extensions.Hosting;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.OpenApi.Models;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Threading.Tasks;
  20. namespace AspNetCore5APIWebService
  21. {
  22. public class Startup
  23. {
  24. private readonly IConfiguration _configuration;
  25. public Startup(IConfiguration configuration)
  26. {
  27. _configuration = configuration;
  28. }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. public void ConfigureServices(IServiceCollection services)
  31. {
  32. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
  33. services.AddControllers();
  34. services.AddHttpClient();
  35. services.AddTransient<IRepository<Person>, RepositoryPerson>();
  36. services.AddTransient<PersonService, PersonService>();
  37. services.AddControllers();
  38. services.AddSwaggerGen(c =>
  39. {
  40. c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetCore5WebApiService", Version = "v1" });
  41. });
  42. }
  43. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  44. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  45. {
  46. if (env.IsDevelopment())
  47. {
  48. app.UseDeveloperExceptionPage();
  49. app.UseSwagger();
  50. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AspNetCore5WebApiService v1"));
  51. }
  52. app.UseHttpsRedirection();
  53. app.UseRouting();
  54. app.UseAuthorization();
  55. app.UseEndpoints(endpoints =>
  56. {
  57. endpoints.MapControllers();
  58. });
  59. }
  60. }
  61. }
Then Add the DB Set Property in your Application Db Context Class
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

Code of Db Context Class is Given Below,

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using DAL.Model;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Configuration;
  7. namespace DAL.Data
  8. {
  9. public class ApplicationDbContext : DbContext
  10. {
  11. public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
  12. {
  13. }
  14. protected override void OnModelCreating(ModelBuilder builder)
  15. {
  16. base.OnModelCreating(builder);
  17. }
  18. public DbSet<Person> Persons { get; set; }
  19. }
  20. }
Step 7
Now start the migration command for creating the table in database
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
After Executing the command, we have the migration folder in our Data Access Layer that contains the definition of person table.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 8
Add the Repository Person class then implement the interface and perform the suitable action according to the action defined in Interface.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code of the file is Given Below,
  1. using DAL.Data;
  2. using DAL.Interface;
  3. using DAL.Model;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace DAL.Repository
  10. {
  11. public class RepositoryPerson : IRepository<Person>
  12. {
  13. ApplicationDbContext _dbContext;
  14. public RepositoryPerson(ApplicationDbContext applicationDbContext)
  15. {
  16. _dbContext = applicationDbContext;
  17. }
  18. public async Task<Person> Create(Person _object)
  19. {
  20. var obj = await _dbContext.Persons.AddAsync(_object);
  21. _dbContext.SaveChanges();
  22. return obj.Entity;
  23. }
  24. public void Delete(Person _object)
  25. {
  26. _dbContext.Remove(_object);
  27. _dbContext.SaveChanges();
  28. }
  29. public IEnumerable<Person> GetAll()
  30. {
  31. try
  32. {
  33. return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();
  34. }
  35. catch (Exception ee)
  36. {
  37. throw;
  38. }
  39. }
  40. public Person GetById(int Id)
  41. {
  42. return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
  43. }
  44. public void Update(Person _object)
  45. {
  46. _dbContext.Persons.Update(_object);
  47. _dbContext.SaveChanges();
  48. }
  49. }
Step 9 - Business Access Layer
Now perform the Business Logic first add the service folder in BAL layer then Add the service person class
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code of Service Person Class is given below
  1. using DAL.Interface;
  2. using DAL.Model;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace BAL.Service
  9. {
  10. public class PersonService
  11. {
  12. private readonly IRepository<Person> _person;
  13. public PersonService(IRepository<Person> perosn)
  14. {
  15. _person = perosn;
  16. }
  17. //Get Person Details By Person Id
  18. public IEnumerable<Person> GetPersonByUserId(string UserId)
  19. {
  20. return _person.GetAll().Where(x => x.UserEmail == UserId).ToList();
  21. }
  22. //GET All Perso Details
  23. public IEnumerable<Person> GetAllPersons()
  24. {
  25. try
  26. {
  27. return _person.GetAll().ToList();
  28. }
  29. catch (Exception)
  30. {
  31. throw;
  32. }
  33. }
  34. //Get Person by Person Name
  35. public Person GetPersonByUserName(string UserName)
  36. {
  37. return _person.GetAll().Where(x => x.UserEmail == UserName).FirstOrDefault();
  38. }
  39. //Add Person
  40. public async Task<Person> AddPerson(Person Person)
  41. {
  42. return await _person.Create(Person);
  43. }
  44. //Delete Person
  45. public bool DeletePerson(string UserEmail)
  46. {
  47. try
  48. {
  49. var DataList = _person.GetAll().Where(x => x.UserEmail == UserEmail).ToList();
  50. foreach (var item in DataList)
  51. {
  52. _person.Delete(item);
  53. }
  54. return true;
  55. }
  56. catch (Exception)
  57. {
  58. return true;
  59. }
  60. }
  61. //Update Person Details
  62. public bool UpdatePerson(Person person)
  63. {
  64. try
  65. {
  66. var DataList = _person.GetAll().Where(x => x.IsDeleted!=true).ToList();
  67. foreach (var item in DataList)
  68. {
  69. _person.Update(item);
  70. }
  71. return true;
  72. }
  73. catch (Exception)
  74. {
  75. return true;
  76. }
  77. }
  78. }
  79. }
Step 10
Again, Modify the Start-Up Class for Adding Transient to register the service business Layer and Data Access Layers, classes
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Code of the Start-up is given below.
  1. using BAL.Service;
  2. using DAL.Data;
  3. using DAL.Interface;
  4. using DAL.Model;
  5. using DAL.Repository;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.HttpsPolicy;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.EntityFrameworkCore;
  11. using Microsoft.Extensions.Configuration;
  12. using Microsoft.Extensions.DependencyInjection;
  13. using Microsoft.Extensions.Hosting;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.OpenApi.Models;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Threading.Tasks;
  20. namespace AspNetCore5APIWebService
  21. {
  22. public class Startup
  23. {
  24. private readonly IConfiguration _configuration;
  25. public Startup(IConfiguration configuration)
  26. {
  27. _configuration = configuration;
  28. }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. public void ConfigureServices(IServiceCollection services)
  31. {
  32. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
  33. services.AddControllers();
  34. services.AddHttpClient();
  35. services.AddTransient<IRepository<Person>, RepositoryPerson>();
  36. services.AddTransient<PersonService, PersonService>();
  37. services.AddControllers();
  38. services.AddSwaggerGen(c =>
  39. {
  40. c.SwaggerDoc("v1", new OpenApiInfo { Title = "AspNetCore5WebApiService", Version = "v1" });
  41. });
  42. }
  43. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  44. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  45. {
  46. if (env.IsDevelopment())
  47. {
  48. app.UseDeveloperExceptionPage();
  49. app.UseSwagger();
  50. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AspNetCore5WebApiService v1"));
  51. }
  52. app.UseHttpsRedirection();
  53. app.UseRouting();
  54. app.UseAuthorization();
  55. app.UseEndpoints(endpoints =>
  56. {
  57. endpoints.MapControllers();
  58. });
  59. }
  60. }
  61. }
Step 11
Add the Person Details API Controller for getting PUT POST AND DELETE endpoints
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
After adding the controller in the API project
Code of the Controller for Person Details is Given Below,
  1. using BAL.Service;
  2. using DAL.Interface;
  3. using DAL.Model;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.Extensions.Logging;
  7. using Newtonsoft.Json;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. namespace AspNetCore5APIWebService.Controllers
  13. {
  14. [Route("api/[controller]")]
  15. [ApiController]
  16. public class PersonDetailsController : ControllerBase
  17. {
  18. private readonly PersonService _personService;
  19. private readonly IRepository<Person> _Person;
  20. public PersonDetailsController(IRepository<Person> Person, PersonService ProductService)
  21. {
  22. _personService = ProductService;
  23. _Person = Person;
  24. }
  25. //Add Person
  26. [HttpPost("AddPerson")]
  27. public async Task<Object> AddPerson([FromBody] Person person)
  28. {
  29. try
  30. {
  31. await _personService.AddPerson(person);
  32. return true;
  33. }
  34. catch (Exception)
  35. {
  36. return false;
  37. }
  38. }
  39. //Delete Person
  40. [HttpDelete("DeletePerson")]
  41. public bool DeletePerson(string UserEmail)
  42. {
  43. try
  44. {
  45. _personService.DeletePerson(UserEmail);
  46. return true;
  47. }
  48. catch (Exception)
  49. {
  50. return false;
  51. }
  52. }
  53. //Delete Person
  54. [HttpPut("UpdatePerson")]
  55. public bool UpdatePerson(Person Object)
  56. {
  57. try
  58. {
  59. _personService.UpdatePerson(Object);
  60. return true;
  61. }
  62. catch (Exception)
  63. {
  64. return false;
  65. }
  66. }
  67. //GET All Person by Name
  68. [HttpGet("GetAllPersonByName")]
  69. public Object GetAllPersonByName(string UserEmail)
  70. {
  71. var data = _personService.GetPersonByUserName(UserEmail);
  72. var json = JsonConvert.SerializeObject(data, Formatting.Indented,
  73. new JsonSerializerSettings()
  74. {
  75. ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
  76. }
  77. );
  78. return json;
  79. }
  80. //GET All Person
  81. [HttpGet("GetAllPersons")]
  82. public Object GetAllPersons()
  83. {
  84. var data = _personService.GetAllPersons();
  85. var json = JsonConvert.SerializeObject(data, Formatting.Indented,
  86. new JsonSerializerSettings()
  87. {
  88. ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
  89. }
  90. );
  91. return json;
  92. }
  93. }
  94. }

RESTful Web Service Results

Debug the project using visual studio Debugger
Swagger is already implemented in our project for documenting the web service in this project we have separate endpoints for getting POST DELETE AND PUT
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
For add the person we have add person endpoint that gives us the JSON object for sending the complete JSON object in the database.

POST Endpoint in Web API Service

If we want to Create the New Person in the database, we must send the JSON object to the endpoints then data is posted by swagger UI to POST endpoint in the controller then create person object creates the complete person object in the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

DELETE Endpoint in Web API Service

For deletion of person, we have a separate endpoint delete employee from the database, we must send the JSON object to the end point then data is posted by swagger UI to call the endpoint DELETE person in the controller then person object will be deleted from the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

GET All Endpoint in Web API Service

We have separate endpoints for all the operations like get all the person records from the Database by Hitting the GET endpoint that sends the request to the controller and in the controller, we have the separate End Point for Fetching all the records from the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

GET End Point for Getting the Record by User Email

We have separate endpoints for all the operations like Get the record of the person by user email from the database by hitting the GET endpoint that sends the request to the controller and in the controller we have the separate endpoint for fetching the record based on user email from the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

Delete End Point for Deleting the Record by User Email

We have separate endpoints for all the operations like delete the record of the person by user email from the database by hitting the DELETE endpoint that sends the request to the controller and in the controller we have a separate Endpoint for deleting the record based on User Email from the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

Update End Point for Updating the Record by User Email

We have separate endpoints for all the operations like updating the record of the person by user email from the database by hitting the UPDATE endpoint that sends the request to the controller and in the controller, we have the separate End Point for Updating the record based on user email from the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API

Testing the RESTful Web Service

Step 1 - Run the Project
Run the project then in the browser swagger UI will be shown to the tester.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 2 - Test POST End Point
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Now Click on Try Out Button then and then send the JSON Object to the AddPerson End Point that is already defined in our controller.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
We have sent the JSON object to the endpoint of API as shown in the figure and the Response Body for this call is true means that our one object is created in the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Click the try out button to get the get all records
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 4 - Test DELETE End Point
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Now click on the try out button then and then send the JSON object to the Delete endpoint that is already defined in our controller.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
We have sent the user email to the endpoints of API as shown in the figure and the response body for this call is true means that our one object is deleted in the database.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Step 5 - Test GET by User Email End Point
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Now click on the try-out button then and then send the JSON object to the GET endpoint that is already defined in our controllers for getting a record based on person email.
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
We get the data from the database according to the user gmail Id
How To Develop A RESTful Web Service In ASP.NET Core 5 Web API
Project Resource Guideline
  • First, download the given Project from my GitHub repository / from article resources.
  • Open the project using visual studio
  • Go to package manager console
  • Add the migration
  • Update the database
  • Run the project
  • Enjoy the beauty of web service API with swagger UI
“Happy API Development”

Conclusion

As a software engineer my opinion about RESTfull web services are a lightweight maintainable and scalable service that is built on the REST architecture. RESTfull architecture provides us the best way to develop cross platfroms application using the Asp.net Core Web API. I suggest all the online community that develop your Web application using RESTfull Web architecture and follow the best practices of coading for high efficieny of application.