Tuesday, January 7, 2025
Google search engine
HomeGuest BlogsHost ASP.NET Application on Rocky / CentOS / AlmaLinux with Apache

Host ASP.NET Application on Rocky / CentOS / AlmaLinux with Apache

In this tech-driven world, the concept of programming and programming languages can not be ignored at all. Programming can be defined as writing instructions in a machine language for a computer to execute. If you are learning C#, then you should be prepared to encounter a lot of “dot net”: .NET, .NET Framework, .NET Core, dotnet, ASP.NET etc.

Dotnet(.NET) is an open-source developer platform, developed by Microsoft, for building innumerable types of applications. These applications can be written in C#, F#, Visual C++, or Visual Basic.”. In other words, .NET can be described as a tool that enables us to build and run C# programs.

Once .NET is installed, you have a bunch of multiple languages, editors, and libraries that can help you:

  • Translate your C# code into instructions that a computer can understand
  • Define a set of data types that make it easier for you to store information in your programs, like text, numbers, and dates
  • Provide utilities for building software, like tools for printing text to the screen and finding the current time

The .NET Core is the new, cross-platform version of .NET. This version can be installed on Windows, macOS, and Linux computers because it’s more flexible and Microsoft is actively enhancing this version. Most people prefer calling it “.NET” instead of .NET Core

What is ASP.NET?

In case you want to build programs specifically for the web, like websites, you probably need to add some tools on top of your .NET installation. One of these tools is ASP.NET. To make it distinct from .NET, developers refer to .NET as a platform and ASP.NET as a framework.

ASP.NET is a free web framework with which you can build amazing websites with HTML, CSS, and JavaScript. It can also be used to create Web APIs and use real-time technologies like Web Sockets. It offers 3 frameworks for creating web applications, these are Web Forms, ASP.NET MVC, and ASP.NET Web Pages.

ASP.NET is preferred because of the following features and benefits:

  • Active community and open-source: This community provides quick answers to questions with an active community of developers on Stack OverflowMicrosoft Q&A, and more.
  • Build secure apps: It supports industry-standard authentication protocols with built-in features to help protect your apps against cross-site scripting (XSS) and cross-site request forgery (CSRF).
  • Fast and scalable: It performs faster than any popular web framework in the independent TechEmpower benchmarks.
  • Free hosting on Azure: There is a free hosting for 10 ASP.NET websites on Microsoft Azure. You can also deploy it to any major cloud platform, or own Linux or Windows servers.

Today, I will take you through how to host ASP.NET Applications on Rocky / CentOS / AlmaLinux with Apache.

#1. Install .NET on Rocky / CentOS / AlmaLinux

To be able to create websites with ASP.NET, we need to have .NET installed on Rocky / CentOS / AlmaLinux. In this guide, I will provide two ways how to achieve this. The methods covered here are:

  1. Using YUM repository
  2. Using an installer script

Option 1 – Install .NET using YUM

Begin by adding the Microsoft package signing key to your list of trusted keys and the Microsoft package repository to your system.

sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm

Once added, install the .NET SDK that allows you to develop apps with .NET.

sudo yum install dotnet-sdk-7.0

Dependency Tree:

....
Transaction Summary
==============================================================================================
Install  10 Packages

Total download size: 182 M
Installed size: 504 M
Is this ok [y/N]: y

Once installed, you do not need to you don’t need to install the corresponding runtime. The ASP.NET Core Runtime allows you to run the apps that were made with .NET that didn’t provide the runtime.

sudo yum install aspnetcore-runtime-7.0

An alternative to the ASP.NET Core Runtime is the .NET Runtime which doesn’t provide support for ASP.NET Core. This can be installed with the command:

sudo yum install dotnet-runtime-7.0

Once installed, check the version with the command:

$ dotnet --version
7.0.101

Option 2 – Install .NET using an installer script

This installer script automatically installs and configures the system for you. To download the installer by clicking on Dotnet installer. You can also pull the script for Dotnet 7 with the command:

wget https://dot.net/v1/dotnet-install.sh

Once downloaded, make the script executable:

sudo chmod +x ./dotnet-install.sh

The script will install the latest long-term support (LTS) SDK version. To install .NET, run the command:

./dotnet-install.sh --version latest

You can also install the latest major version, say 7.0 using the command:

./dotnet-install.sh --channel 7.0

Once complete, export your DOTNET_ROOT and PATH.

export DOTNET_ROOT=$HOME/.dotnet
export PATH=$PATH:$HOME/.dotnet:$HOME/.dotnet/tools

Now verify the installation:

$ dotnet --version
6.0.404

#2. Creating ASP.NET Application

Once .NET is installed, we can proceed and create a sample web application. For this guide, we will create a sample application named my-app

dotnet new web --output my-app

Sample Output

The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /home/rocky9/my-app/my-app.csproj...
  Determining projects to restore...
  Restored /home/rocky9/my-app/my-app.csproj (in 85 ms).
Restore succeeded.

After this, you will have an application directory my-app created with all the required dependencies. This is a simple Hello World web application created from a template.

You can now modify your application as desired. For example, by removing the HTTPS URL, you can also provide the desired port for HTTP as shown:

$ vim my-app/Properties/launchSettings.json
....
  "profiles": {
    "my_app": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
.....

If you want the application to run at the insecure endpoint, Deactivate HTTPS Redirection Middleware in the Development environment, and modify the Program.cs file by adding the lines:

if (!app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
}

To run the application, we will use the command:

dotnet run --project my-app

Sample Output:

Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/rocky9/my-app/

Now on another shell, verify if the application is running on the provided port

$ curl http://localhost:5000
Hello World!

This shows that the web app is working as desired. So we can stop the process using CRTL+C and kill the service on the port:

sudo killall -9 my-app

#3. Publish ASP.NET applications

Once the application is running, we can publish it. Publishing can be defined as packaging an app into the desired directory.

The available methods to publish applications are:

  • Single-file application: this is self-contained and can be deployed as a single executable with all dependent files contained in a single binary.
  • Framework-dependent deployment (FDD): The application uses a shared system-wide version of .NET.
  • Self-contained deployment (SCD): This method uses a .NET runtime built by Microsoft.

For this guide, we will publish a framework-dependent application. Create the directory to publish your application to:

sudo mkdir -p /var/www/html/my-app
sudo chown -R $USER /var/www/html/my-app

Publish the app using the command:

dotnet publish my-app -f net7.0 -c Release -o /var/www/html/my-app

Remember to provide the version of .NET installed(net7.0) before you proceed.

Optional: you can also publish the app as a Self-contained deployment to trim dependencies. For example for RHEL only, the command can be:

dotnet publish my-app -f net7.0 -c Release -o /var/www/html/my-app -r rhel.8-architecture --self-contained false

#4. Install and Configure Apache Proxy

Install the Apache web server on Rocky / CentOS / AlmaLinux with the command:

sudo yum -y install httpd mod_ssl

Once installed, create the virtual host file for your application:

sudo vim /etc/httpd/conf.d/helloapp.conf

Add the lines below:

<VirtualHost *:*>
    RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
</VirtualHost>

<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
    ServerName www.test.geeksforgeeks.org
    ServerAlias *test.geeksforgeeks.org
    ErrorLog /var/log/httpd/helloapp-error.log
    CustomLog  /var/log/httpd/helloapp-access.log common
</VirtualHost>

Ensure that the hostname is added in /etc/hosts accordingly. Now restart the service:

sudo systemctl restart httpd
sudo systemctl enable httpd

Allow port 80 through the firewall:

#FOR UFW
sudo ufw allow 80

##FOR Firewalld
sudo firewall-cmd --add-port=80/tcp --permanent
sudo firewall-cmd --reload

#5. Create a systemd Service for the Application

You can now create a system service file for your ASAP.NET application.

sudo vim /etc/systemd/system/helloapp.service

In the file, add the below lines replacing where required:

[Unit]
Description=Example .NET Web API App running on CentOS/Rocky/Alma

[Service]
WorkingDirectory=/var/www/html/my-app
ExecStart=/usr/bin/dotnet /var/www/html/my-app/my-app.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=neveropen
Group=apache
Environment=ASPNETCORE_ENVIRONMENT=Production 

[Install]
WantedBy=multi-user.target

Identify the exact path of your .NET installation and replace it at ExecStart before you proceed.

$ which dotnet
/usr/bin/dotnet

You may also need to provide the system user if you used the installer script.

$ echo $USER
neveropen

Disable SELinux or set it in permissive mode

sudo setenforce 0

Save the file, start and enable the service:

sudo systemctl start helloapp.service
sudo systemctl enable helloapp.service

Verify if the service is running:

$ systemctl status helloapp.service
 helloapp.service - Example .NET Web API App running on CentOS/Rocky/Alma
     Loaded: loaded (/etc/systemd/system/helloapp.service; enabled; vendor preset: disabled)
     Active: active (running) since Mon 2022-12-19 08:59:19 CET; 8s ago
   Main PID: 76804 (dotnet)
      Tasks: 14 (limit: 23441)
     Memory: 17.0M
        CPU: 453ms
     CGroup: /system.slice/helloapp.service
             └─76804 /home/rocky9/.dotnet/dotnet /var/www/html/my-app/my-app.dll

Now you will have the service running on the set port:

$ sudo ss -plunt|grep 5000
tcp   LISTEN 0      512        127.0.0.1:5000       0.0.0.0:*    users:(("dotnet",pid=76804,fd=114))                                                                        
tcp   LISTEN 0      512            [::1]:5000          [::]:*    users:(("dotnet",pid=76804,fd=116))  

Allow this service through SELinux:

sudo semanage port -a -t http_port_t -p tcp 5000

#6. Access your ASP.NET Application

You can now access the application using the URL http://domain_name. If all is okay, you will see your application as shown:

ASP.NET Application on RockyCentOSAlmaLinux with Apache

Conclusion

Today we have learned how to host ASP.NET Applications on Rocky / CentOS / AlmaLinux with Apache. Now you have apache set to forward requests from http://127.0.0.1:5000 to http://localhost:80. We also have a systemd service that can be used to start and monitor the ASP.NET app. I hope this was significant.

See more:

RELATED ARTICLES

Most Popular

Recent Comments