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.
Select empty project template, we will add other required files and dependencies later.
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.
- app.UseEndpoints(endpoints =>
- {
- throw new Exception("Test Exception");
-
-
-
-
- });
If we run the application, we can see the below developer-friendly exception page that will display the error,
This error page is controlled by below code,
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
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,
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 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.
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”.
- app.UseEndpoints(endpoints
- {
- endpoints.MapControllers();
- });
Once we run the application with the “api/employee”, the GET endpoint returns the test data.
Add Test to the API endpoint
We will add the below “Employee” test data repository code to generate the test data.
- public class EmployeeTestRepository : IEmployeeRepository
- {
- public List<Employee> GetAllEmployee()
- {
- var rng = new Random();
- var employesData = Enumerable.Range(1, 5).Select(index => new Employee
- {
- EmployeeId = rng.Next(-20, 55),
- Email = "Test" + rng.Next(-20, 55) + "@test.com",
- EmployeeName = "Test Name" + rng.Next(-20, 55),
- Skill = "Test Skill" + rng.Next(-20, 55)
- })
- .ToList();
-
- return employesData;
- }
- }
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
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- services.AddScoped<IEmployeeRepository, EmployeeTestRepository>();
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
EmployeeController.cs
- [ApiController]
- [Route("api/[controller]")]
- public class EmployeeController : ControllerBase
- {
-
- private readonly ILogger<EmployeeController> _logger;
- private readonly IEmployeeRepository _employeeRepository;
-
- public EmployeeController(ILogger<EmployeeController> logger, IEmployeeRepository employeeRepository)
- {
- _logger = logger;
- _employeeRepository = employeeRepository;
- }
-
-
- [HttpGet]
- public List<Employee> Get()
- {
- return GetEmployees();
- }
-
- private List<Employee> GetEmployees()
- {
- return _employeeRepository.GetAllEmployee();
- }
-
- }
Run the application to see the sample data:
Summary
In this post, we learned about .NET core and created an API application with test data.