Create a .NET Core API Application

Introduction

 
In this post, we will learn about .NET Core and creating an API Application with Test Repository.
 

About .NET Core 

 
.NET Core is a free and open-source, managed computer software framework for Windows, Linux, and macOS operating systems. It is a cross-platform successor to. NET Framework.
 
Basically these are console applications based on the type of project and Hosting methods. It will have additional components.
 
Main Features
  • Supports Cross-platform - Runs on Windows, macOS, and Linux.
  • Open-source project supported by Microsoft.
  • Compatible with existing .NET Framework, Mono and Xamarin through .NET standard.

Create a .NET core Application

 
Prerequisites
  • Visual Studio 2019 (any edition).
  • .NET Core 3 or above.
Create a .NET core empty application in Visual studio, by selecting the below project templates. We can select “ASP.NET core Web Application” template.
 
Create .Net Core API Application
 
Create .Net Core API Application
 
Select empty project template, we will add other required files and dependencies later.
 
Create .Net Core API Application
 
Once the project has been created we can see that the“program.cs” and “startup.cs” files will be generated. Both files help to start and load .NET core required modules. It also, they help to add .NET Core Middleware applications.
 
.NET core pipelines/middleware components are similar to older ASP.NET Handlers and Modules component. For example, .NET core pipelines: Diagnostics, Routing and Authentication.
 

About the Developer Exception page in .NET Core

 
In “startup.cs”, we have written the below manual exception code to throw the error.
  1. app.UseEndpoints(endpoints =>  
  2.             {  
  3.                 throw new Exception("Test Exception");  
  4.                 //endpoints.MapGet("/", async context =>  
  5.                 //{  
  6.                 //    await context.Response.WriteAsync("Hello World!");  
  7.                 //});  
  8.             });  
If we run the application, we can see the below developer-friendly exception page that will display the error,
 
Create .Net Core API Application
 
This error page is controlled by below code,
  1. if (env.IsDevelopment())  
  2. {  
  3.     app.UseDeveloperExceptionPage();  
  4. }  
If its in the Development environment, we can see the above page. We can set the environment variable for our core application in Project Properties-> Debug page,
 
Create .Net Core API Application
 
We don’t need to use “app.UseMvc()” instead we can use “app.UseRouting()” in .NET core 3 onwards. Otherwise, we will get the below error:
 
Create .Net Core API Application
 

Create API controller with Routing

 
We can create the “Controllers” folder and class file or API controller file and make sure it's inherited from the “ControllerBase” class. We also added the “ApiController” and “Route” attribute which helps to access the API endpoints.
 
Create .Net Core API Application
 
The below code uses the “convention” based API routing. When we add new controllers, we don’t need to change the code. For Example: if we have controller name “EmployeeController” and API endpoint will be access like “api\employee”.
  1. app.UseEndpoints(endpoints   
  2. {  
  3.      endpoints.MapControllers();  
  4. });  
Once we run the application with the “api/employee”, the GET endpoint returns the test data.
 
Create .Net Core API Application

Add Test to the API endpoint

 
We will add the below “Employee” test data repository code to generate the test data.
  1. public class EmployeeTestRepository : IEmployeeRepository  
  2.    {  
  3.        public List<Employee> GetAllEmployee()  
  4.        {  
  5.            var rng = new Random();  
  6.            var employesData = Enumerable.Range(1, 5).Select(index => new Employee  
  7.            {  
  8.                EmployeeId = rng.Next(-20, 55),  
  9.                Email = "Test" + rng.Next(-20, 55) + "@test.com",  
  10.                EmployeeName = "Test Name" + rng.Next(-20, 55),  
  11.                Skill = "Test Skill" + rng.Next(-20, 55)  
  12.            })  
  13.            .ToList();  
  14.   
  15.            return employesData;  
  16.        }  
  17.    }  
Inject the “EmployeeRepository” in Employee controller. Add the repository injections in startup.cs file.
 
services.AddScoped<IEmployeeRepository, EmployeeTestRepository>();
 
Added the below code for reference:
 
Startup.cs
  1. public class Startup  
  2.   {  
  3.       public void ConfigureServices(IServiceCollection services)  
  4.       {  
  5.           services.AddMvc();  
  6.           services.AddScoped<IEmployeeRepository, EmployeeTestRepository>();  
  7.       }  
  8.   
  9.       // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  10.       public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  11.       {  
  12.           if (env.IsDevelopment())  
  13.           {  
  14.               app.UseDeveloperExceptionPage();  
  15.           }  
  16.            
  17.           app.UseRouting();  
  18.   
  19.           app.UseEndpoints(endpoints =>  
  20.           {  
  21.               endpoints.MapControllers();  
  22.           });  
  23.       }  
  24.   }  
EmployeeController.cs
  1. [ApiController]  
  2. [Route("api/[controller]")]  
  3.    public class EmployeeController : ControllerBase  
  4.    {  
  5.   
  6.        private readonly ILogger<EmployeeController> _logger;  
  7.        private readonly IEmployeeRepository _employeeRepository;  
  8.   
  9.        public EmployeeController(ILogger<EmployeeController> logger, IEmployeeRepository employeeRepository)  
  10.        {  
  11.            _logger = logger;  
  12.            _employeeRepository = employeeRepository;  
  13.        }  
  14.         
  15.        // GET: api/<controller>  
  16.        [HttpGet]  
  17.        public List<Employee> Get()  
  18.        {  
  19.            return GetEmployees();  
  20.        }  
  21.   
  22.        private List<Employee> GetEmployees()  
  23.        {  
  24.            return _employeeRepository.GetAllEmployee();  
  25.        }  
  26.        
  27.    }  
Run the application to see the sample data:
 
Create .Net Core API Application 

Summary

 
In this post, we learned about .NET core and created an API application with test data.


Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles