We run Visual Studio 2022 Community Edition and we create a new project
We select the project template
We input the location and the project name
We chose the new project main features
wwwroot
This folder contains static files like HTML, CSS, JavaScript, and image files. It's the root for web server requests.
Controllers
In an MVC (Model-View-Controller) application, this folder contains the controller classes. Controllers handle user input and interactions, and return responses.
Models
This folder holds the classes that represent the data of the application and the logic to manage that data. It's part of the MVC pattern.
Views
In MVC, the Views folder contains the Razor view files (.cshtml). These files combine HTML markup with C# code for dynamic rendering of content.
Properties
Contains configuration files, like launchSettings.json, which includes settings for launching the app, like environment variables and application URL.
Dependencies
This section in your solution explorer lists the packages, frameworks, and projects your app depends on.
Optional Folders
Areas: Used for organizing related functionality into a group, like admin panels.
Migrations: For Entity Framework Core, contains database migration files.
Data: Contains data access related code, often includes a DbContext class for Entity Framework Core.
This is the workflow summary:
Program.cs is the application entry point -> https://localhost:44327/Home/Index -> Call Index action inside the Home controller Controllers/HomeController.cs -> Call Home view (Views/Home/Index.cshtml) -> the Index.cshtl view is Rendered inside the Views/Shared/_Layout.cshtml as defined in _ViewStart.cshtml
It sets up the web host and starts the application.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
3.2. The application entry point (/Home/Index) calls the Index action inside the Home controller (Controllers/HomeController.cs)
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/WebApplication1.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication1</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2024 - WebApplication1 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
We right click on the project name and we select the menu option Add->Docker support...
We select the Linux operating system
This is the Dockerfile automatically created
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WebApplication1.csproj", "."]
RUN dotnet restore "./././WebApplication1.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./WebApplication1.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./WebApplication1.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]
We right click on the project name and we select the option Open in Terminal
We build the WebApp docker image running this command
docker build -t webapplication1 .
We can verify in Docker Desktop the new image
We run the docker image with this command
docker run -d -p 8080:8080 --name myapp webapplication1
We confirm the application is running in the endpoing: http://localhost:8080
We also see the running docker image in Docker Desktop
Creating and using a self-signed certificate for local development involves a few steps.
This process can vary slightly depending on your operating system. I'll outline the general steps and provide guidance for Windows:
You can use PowerShell to create a self-signed certificate:
New-SelfSignedCertificate -DnsName localhost -CertStoreLocation cert:\LocalMachine\My
We copy the Thumbprint. We need it to look for our certificate inside the Manage Certificates Computer application in the Personal/Certificates folder
Thumbprint: 8CC1EAD679D28909645182A946212D1126AB9192
This command creates a certificate for localhost and places it in the local machine's certificate store.
We look for the application Manage Computer Certificates (Microsoft Management Console (MMC)) and we run it
We search for the new certificate inside the Personal/Certificates folder, also Issue To: localhot and with the Thumbprint: 8CC1EAD679D28909645182A946212D1126AB9192
We also check the certificate Thumbprint: 8CC1EAD679D28909645182A946212D1126AB9192
You need to export the certificate to a .pfx file with a password. You can do this through the Microsoft Management Console (MMC) or PowerShell.
We select the certificate and then select the menu option Action->All Tasks->Export...
We click on the Next button
We select the option Yes, export the private key
We select the option Personal Information Exchange PFX
We select and input the Password: 123456
We press in the Browser button and select the certificate name and the location to store it
We press the Save button
We click on the Next button
We press the Finish button
You can trust the certificate by adding it to the "Trusted Root Certification Authorities" store, either through MMC or PowerShell.
We select the certificate and right click on it and select the copy option
We select the Certificates folder inside the folder Trusted Root Certification Authorities and we right click on it and select the option paste
In your appsettings.json or programmatic configuration, specify the path to the .pfx file and the password you used during export:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://*:8081",
"Certificate": {
"Path": "certificate.pfx",
"Password": "123456"
}
},
"Http": {
"Url": "http://*:8080"
}
}
}
}
Also modify the Dockefile to copy the certificate file into the Docker image: COPY ["certificate.pfx", "."]
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WebApplication1.csproj", "."]
RUN dotnet restore "./WebApplication1.csproj"
COPY . .
WORKDIR "/src"
RUN dotnet build "WebApplication1.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "WebApplication1.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# Copy the certificate file into the Docker image
COPY ["certificate.pfx", "."]
ENTRYPOINT ["dotnet", "WebApplication1.dll"]
For accessing both protocol HTTP and HTTPS comment this line: app.UseHttpsRedirection(); in Program.cs file
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
We create the WebApp docker image running this command
docker build -t webapplication1 .
We execute the following command to run the docker container
docker run -d -p 8080:8080 -p 8081:8081 --name myapp webapplication1
We also can verify the running container in the Docker Desktop