ASP.NET Core 8 Web API -

Deployment

Deploying an ASP.NET Core 8 Web API involves various steps and considerations to ensure your application runs smoothly in different environments. This guide covers deployment strategies, configurations, and best practices for deploying your Web API to various platforms, including Azure, AWS, Docker, Linux, and IIS on Windows Server.


1. Introduction to Deployment

Deployment is the process of distributing your application to a server where it can be accessed by users. Proper deployment ensures your application is reliable, scalable, and secure.

2. Preparing Your Application for Deployment

Before deploying, ensure your application is production-ready.

2.1 Configure Your Project Update your project file (.csproj) to ensure it is set up correctly for deployment.
        
            
<PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <AssemblyName>YourApiProject</AssemblyName>
</PropertyGroup>

        
    

Key Properties:

2.2 Configure Application Settings Update your appsettings.json and appsettings.Development.json files to manage environment-specific configurations.
        
            
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "AllowedHosts": "*"
}

        
    

Key Properties:

2.3 Configure Environment Variables Set environment variables in your hosting environment to manage sensitive data and environment-specific settings.
        
            
export ASPNETCORE_ENVIRONMENT=Production
export ConnectionStrings__DefaultConnection="YourProductionDatabaseConnectionString"

        
    

Key Environment Variables:


3. Deployment to Azure

Azure is a popular cloud platform for deploying ASP.NET Core applications.

3.1 Deploying to Azure App Service Step-by-Step Guide:
  1. Create an Azure App Service:
    • Navigate to the Azure portal.
    • Create a new App Service.
    • Configure the App Service Plan (e.g., location, size).
  2. Publish from Visual Studio:
    • Right-click on your project in Visual Studio.
    • Select "Publish".
    • Choose "Azure" and select "Azure App Service (Windows)".
    • Follow the prompts to publish your application.
  3. Configure App Service Settings:
    • Navigate to your App Service in the Azure portal.
    • Go to "Configuration" > "Application settings".
    • Add your environment variables and connection strings.

Key Configuration Settings:

3.2 Deploying to Azure Kubernetes Service (AKS) Step-by-Step Guide:
  1. Create an AKS Cluster:
    • Navigate to the Azure portal.
    • Create a new Kubernetes service.
    • Configure the cluster settings (e.g., node size, node count).
  2. Containerize Your Application:
    • Create a Dockerfile in your project.
    Dockerfile:
            
                
    FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
    WORKDIR /app
    EXPOSE 80
    
    FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
    WORKDIR /src
    COPY ["YourApiProject.csproj", "./"]
    RUN dotnet restore "./YourApiProject.csproj"
    COPY . .
    WORKDIR "/src/."
    RUN dotnet build "YourApiProject.csproj" -c Release -o /app/build
    
    FROM build AS publish
    RUN dotnet publish "YourApiProject.csproj" -c Release -o /app/publish
    
    FROM base AS final
    WORKDIR /app
    COPY --from=publish /app/publish .
    ENTRYPOINT ["dotnet", "YourApiProject.dll"]
    
            
        
  3. Push the Docker Image to Azure Container Registry (ACR):
    • Build and push the image to ACR.
            
                
    az acr build --registry <your_acr_name> --image your-api-project:latest .
    
            
        
  4. Deploy to AKS:
    • Create Kubernetes deployment and service files.
    • Apply the configuration using kubectl.
    k8s-deployment.yaml:
            
                
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: your-api-project
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: your-api-project
      template:
        metadata:
          labels:
            app: your-api-project
        spec:
          containers:
          - name: your-api-project
            image: <your_acr_name>.azurecr.io/your-api-project:latest
            ports:
            - containerPort: 80
    
            
        

            
                
    kubectl apply -f k8s-deployment.yaml
    
            
        

Key Components:


4. Deployment to AWS

AWS offers several services for deploying ASP.NET Core applications, including Elastic Beanstalk and ECS.

4.1 Deploying to AWS Elastic Beanstalk Step-by-Step Guide:
  1. Create an Elastic Beanstalk Environment:
    • Navigate to the AWS Management Console.
    • Create a new Elastic Beanstalk application.
    • Create an environment (e.g., Web Server Environment).
  2. Publish from Visual Studio:
    • Right-click on your project in Visual Studio.
    • Select "Publish".
    • Choose "AWS Elastic Beanstalk".
    • Follow the prompts to publish your application.
  3. Configure Environment Settings:
    • Navigate to your Elastic Beanstalk environment in the AWS Management Console.
    • Go to "Configuration" > "Software".
    • Add your environment variables and connection strings.

Key Configuration Settings:

4.2 Deploying to AWS ECS Step-by-Step Guide:
  1. Create an ECS Cluster:
    • Navigate to the AWS Management Console.
    • Create a new ECS cluster.
    • Configure the cluster settings (e.g., EC2 or Fargate).
  2. Containerize Your Application:
    • Create a Dockerfile (as shown in the Azure Kubernetes example).
  3. Push the Docker Image to Amazon ECR:
    • Build and push the image to Amazon ECR.
            
                aws ecr create-repository --repository-name your-api-project
    $(aws ecr get-login --no-include-email --region us-west-2)
    docker build -t your-api-project .
    docker tag your-api-project:latest <aws_account_id>.dkr.ecr.us-west-2.amazonaws.com/your-api-project:latest
    docker push <aws_account_id>.dkr.ecr.us-west-2.amazonaws.com/your-api-project:latest
            
        
  4. Deploy to ECS:
    • Create ECS task definition and service files.
    • Apply the configuration using the AWS CLI or Management Console.
    ecs-task-definition.json:
            
                
    {
      "family": "your-api-project",
      "networkMode": "awsvpc",
      "containerDefinitions": [
        {
          "name": "your-api-project",
          "image": "<aws_account_id>.dkr.ecr.us-west-2.amazonaws.com/your-api-project:latest",
          "essential": true,
          "portMappings": [
            {
              "containerPort": 80,
              "protocol": "tcp"
            }
          ]
        }
      ]
    }
    
            
        

            
                
    aws ecs create-cluster --cluster-name your-api-cluster
    aws ecs register-task-definition --cli-input-json file://ecs-task-definition.json
    aws ecs create-service --cluster your-api-cluster --service-name your-api-service --task-definition your-api-project --desired-count 3
    
            
        

Key Components:


5. Deployment with Docker

Docker allows you to containerize your application and run it consistently across different environments.

5.1 Create a Dockerfile
        
            
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["YourApiProject.csproj", "./"]
RUN dotnet restore "./YourApiProject.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "YourApiProject.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "YourApiProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "YourApiProject.dll"]

        
    
5.2 Build and Run the Docker Image
        
            
docker build -t your-api-project .
docker run -d -p 8080:80 your-api-project

        
    

Key Components:


6. Deployment to Linux

Deploying an ASP.NET Core application to a Linux server involves setting up the server, configuring the environment, and deploying the application.

6.1 Prepare the Linux Server Install .NET Core Runtime:

Follow the official Microsoft documentation to install the .NET runtime on your Linux distribution.

Example for Ubuntu:
        
            
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y aspnetcore-runtime-8.0

        
    
Install Nginx:
        
            
sudo apt-get install nginx

        
    
Configure Nginx:

Create an Nginx configuration file for your application.

Example Nginx Configuration (/etc/nginx/sites-available/default):
        
            
server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

        
    
Start Nginx:
        
            
sudo systemctl start nginx
sudo systemctl enable nginx

        
    
6.2 Deploy the Application Publish Your Application:
        
            
dotnet publish -c Release -o ./publish

        
    
Copy the Application to the Server:
        
            
scp -r ./publish user@yourlinuxserver:/var/www/your-api-project

        
    
Create a Systemd Service:

Create a systemd service file to manage your application.

Example Systemd Service (/etc/systemd/system/your-api-project.service):
        
            
[Unit]
Description=Your API Project
After=network.target

[Service]
WorkingDirectory=/var/www/your-api-project
ExecStart=/usr/bin/dotnet /var/www/your-api-project/YourApiProject.dll
Restart=always
RestartSec=10
SyslogIdentifier=your-api-project
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production

[Install]
WantedBy=multi-user.target

        
    
Start and Enable the Service:
        
            
sudo systemctl start your-api-project
sudo systemctl enable your-api-project

        
    

Key Components:


7. Deployment to IIS on Windows Server

Deploying to IIS involves setting up the server, configuring IIS, and deploying the application.

7.1 Prepare the Windows Server Install IIS:

Use the Server Manager to install the Web Server (IIS) role and include the ASP.NET Core Hosting Bundle.

Install the ASP.NET Core Hosting Bundle:

Download and install the ASP.NET Core Hosting Bundle from the Microsoft website.

7.2 Configure IIS Create a New Site in IIS: Configure Application Pool: 7.3 Deploy the Application Publish Your Application:
        
            
dotnet publish -c Release -o ./publish

        
    
Copy the Application to the Server:

Use a tool like FileZilla or Windows Explorer to copy the published files to the IIS server.

Configure Permissions:

Ensure the application pool identity has read and execute permissions on the application folder.

Key Components:


8. Best Practices for Deployment


Comprehensive Example for Azure Deployment

Program.cs:
        
            
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using YourApiProject.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddScoped<IProductsService, ProductsService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        options.RoutePrefix = string.Empty; // Serve the Swagger UI at the app's root
    });
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

        
    
Dockerfile:
        
            
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["YourApiProject.csproj", "./"]
RUN dotnet restore "./YourApiProject.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "YourApiProject.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "YourApiProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "YourApiProject.dll"]

        
    
Kubernetes Deployment File (k8s-deployment.yaml):
        
            
apiVersion: apps/v1
kind: Deployment
metadata:
  name: your-api-project
spec:
  replicas: 3
  selector:
    matchLabels:
      app: your-api-project
  template:
    metadata:
      labels:
        app: your-api-project
    spec:
      containers:
      - name: your-api-project
        image: <your_acr_name>.azurecr.io/your-api-project:latest
        ports:
        - containerPort: 80

        
    

Deploying an ASP.NET Core 8 Web API involves configuring your application for various environments and using the appropriate tools and platforms. By following best practices and understanding the key components and configurations, you can ensure a smooth and efficient deployment process. This comprehensive guide provides the knowledge and tools to deploy your ASP.NET Core 8 Web API to Azure, AWS, Docker, Linux, and IIS on Windows Server effectively.