ASP.NET
Basics of the code
|
|
Explaination
Certainly! Let’s break down the provided code snippet line by line. This code is typically found in the Program.cs
file of an ASP.NET Core application and is part of the setup for a minimal API or web application.
Code Breakdown
|
|
- Explanation: This line creates a new instance of a
WebApplicationBuilder
. TheCreateBuilder
method initializes the builder with the command-line arguments passed to the application (args
). This builder is used to configure services and middleware for the application.
|
|
- Explanation: This line adds the Endpoints API Explorer service to the application’s service collection. This service is used to discover and document the API endpoints in your application. It helps in generating metadata about the endpoints, which can be useful for tools like Swagger.
|
|
- Explanation: This line adds the Swagger generator to the service collection. Swagger is a tool that helps document and test APIs. By adding this service, you enable the generation of Swagger documentation for your API endpoints, which can be accessed via a web interface.
|
|
- Explanation: This line builds the
WebApplication
instance using the configured builder. At this point, the application is ready to be configured with middleware and endpoints.
|
|
- Explanation: This line checks if the application is running in the Development environment. The
IsDevelopment()
method is part of theIHostEnvironment
interface, which provides information about the hosting environment.
- Explanation: If the application is in the Development environment, these two lines enable Swagger middleware:
app.UseSwagger()
: This middleware generates the Swagger JSON document that describes the API.app.UseSwaggerUI()
: This middleware sets up the Swagger UI, which is a web interface that allows you to interact with the API endpoints defined in your application. You can access it typically at/swagger
in your browser.
|
|
- Explanation: This line adds middleware that redirects HTTP requests to HTTPS. It ensures that all requests to the application are secure by enforcing the use of HTTPS.
|
|
- Explanation: This line starts the application and begins listening for incoming HTTP requests. It is the final step in the application setup, and once this line is executed, the application is running and ready to handle requests.
Making a simple CRUD application
In order to make a simple application we need to have two thinks working simultaneously, a .NET backend and a database that will manage the data. We will also be using an ORM (Object relational mapping), this reduces our dependencies on directly accessing the database and working with a wrapper.
Content of
Program.cs
- basic driver code1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddControllers(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Hello World!"); app.Run();
Controllers/UserController.cs
- handles req1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; [ApiController] [Route("api/[controller]")] public class UsersController : ControllerBase { private readonly ApplicationDbContext _context; public UsersController(ApplicationDbContext context) { _context = context; } [HttpGet] public async Task<ActionResult<List<User>>> GetUsers() { return await _context.Users.ToListAsync(); } [HttpPost] public async Task<ActionResult<User>> CreateUser(User user) { _context.Users.Add(user); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetUsers), new { id = user.Id }, user); } }
Data/ApplicationDbContext.cs
- middleman of communication to the DB
Making a simple CRUD application - using the EFCore package
To perform Entity Framework Core (EF Core) migrations with PostgreSQL using the Npgsql.EntityFrameworkCore.PostgreSQL
provider and the Microsoft.EntityFrameworkCore.Design
package, follow these steps:
Step 1: Install Required Packages
Make sure you have the necessary NuGet packages installed in your project. You need both
Npgsql.EntityFrameworkCore.PostgreSQL
andMicrosoft.EntityFrameworkCore.Design
. You can install them via the NuGet Package Manager Console or by editing your.csproj
file.Step 2: Create Your DbContext and Models
Define your entity classes and a
DbContext
. For example:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
using Microsoft.EntityFrameworkCore; public class MyDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_password"); } } public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
Step 3: Add a Migration
Once you have your
DbContext
and models set up, you can create a migration. Open the Package Manager Console or terminal and run the following command:1
dotnet ef migrations add InitialCreate
Step 4: Apply the Migration
To apply the migration and create the database schema in your PostgreSQL database, run the following command:
1
dotnet ef database update
- Updating the database: After the initial database is created one may be able to update the database by passing to the migrations, this can be done by repeating Step 3 and Step 4