×
Community Blog Deploying ASP.NET Core App in Visual Studio and Deploying on Simple Application Server

Deploying ASP.NET Core App in Visual Studio and Deploying on Simple Application Server

In this guide, we will be developing an ASP.NET core application in Visual Studio and deploying it on Alibaba cloud Simple Application Server.

By Arnab Choudhuri, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

This article is meant for individual developers or startups with developers who are not familiar with deployments and use PaaS for the same. In this article we look at the steps one has to do to develop their ASP.NET core applications in Visual Studio 2017 and deploy the same on Alibaba Cloud Simple Application Server. Here we will use the edge-origin proxy pattern which will provide the application scalability, data security and performance.

Quick FAQ

What Is Visual Studio?

Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs, as well as websites, web apps, web services and mobile apps.

What Is .NET Core?

.NET Core is an open-source, general-purpose development platform maintained by Microsoft and the .NET community. It's cross-platform (supporting Windows, macOS, and Linux) and can be used to build device, cloud, and IoT applications.

What Is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications.

What Is Kestrel?

Kestrel is a cross-platform web server for ASP.NET Core. Kestrel is the web server that's included by default in ASP.NET Core project templates.

What Is Alibaba Cloud Simple Application Server?

Simple Application Server provides you the all-in-one solution to launch and manage your application, set up domain name resolution, and build, monitor, maintain your website with just a few clicks. It makes private server building much easier, and it is the best way for beginners to get started with Alibaba cloud.

Developing Example Application

Prerequisites

Alibaba Cloud account

If you do not have one already, click on this link to sign up.

Visual Studio

To install Visual Studio for free, visit https://visualstudio.microsoft.com/downloads/

Please ensure you have 'ASP.NET and web development' and '.NET Core cross-platform development' workloads.

Create ASP.NET core project from template

select File > New > Project
select ASP.NET Core Web Application as shown in image below

01

Provide a name to the project 'alibabadotnetcore' and select OK.

In the next screen ensure you have .Net Core and ASP.NET Core2.1 selected in the top drop down boxes and select Web Application from the available options.

As we are not going to have HTTPS in this application please ensure you have Configure for HTTPS option not selected and Select OK.

02

This should create a starter project from template.

Note: The Web Application option enables one to build Razor Pages web applications which are a new way of building asp.net applications with the old code behind style without the baggage of the erstwhile WebForm Applications and makes coding easier and developer more productive.

Edit and Change Code

This is where one would add their own development code. We are going to make a simple change.

Select _Layout.cshtml under the folder Shared under the folder Pages.

In _Layout.cshtml, go to the line of code containing tag with class navbar-brand

Change the line as below

<a asp-page="/Index" class="navbar-brand">Alibaba SAS Demo</a> 

03

Run Application

Press Ctrl+F5 (or Debug > Start Without Debugging). The app opens in a browser.

04

Note: Running in VS+IIS Express will give a random port designated by VS but on server where we will use Kestrel, port 5000 is used on default behavior.

Publish Example Project for Deployment

With Visual Studio 2017, we can package our web application with all of the references needed to run on Linux by building a "Self-Contained Application". This type of deployment does not require a .NET SDK to be installed on a server, and can be deployed to any machine that does not have any .NET features installed.

Prepare the Web Application

Unless your application uses Globalization rules and the data, it is better to go for globalization invariant mode. This ensures you do not need to install additional ICU http://icu-project.org/ packages on linux.

Right click on Project name (not the solution) in Visual Studio Solution Explorer and select Edit alibabadotnetcore.csproj

Add the following line in as shown in image.

<RuntimeHostConfigurationOption Include="System.Globalization.Invariant" Value="true" />

05

Note: Later in the article we are going to install and implement a reverse proxy on the deployment server. A reverse proxy is a common setup for serving dynamic web apps. The reverse proxy terminates the HTTP request and forwards it to the ASP.NET app.

As requests are forwarded by reverse proxy, we need to ensure Headers are forwarded as well, so that redirect URIs and other security policies work correctly. Though this is not required for our simple example application, you will most probably need to do as stated below.

Add the Microsoft.AspNetCore.HttpOverrides package to Startup.cs file.

Add the below code in Startup.Configure before calling any Authentication or similar methods.

app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

Note: In ASP.NET Core, your application is essentially just a console app. You then create and configure your own lightweight HTTP server within your application itself. ASP.NET Core comes with two HTTP servers which you can plug straight in out of the box, one being Kestrel, the new high performance, cross-platform web server built specifically for ASP.NET Core.

It is a good practice to explicitly state the host address and port the webhost will listen on or use a wildcard instead resulting in the web host binding to all IPv4 and IPv6 IPs addresses on specified port via the UseUrls(...) extension method that's available on the IWebHostBuilder interface.

In the Program.cs file, edit the CreateWebHostBuilder method to add UseUrls extension as shown below.

     public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://*:5000")
                .UseStartup<Startup>();

Press Ctrl+F5 to run the application and test that it runs perfectly.

Publish Project as Self-Contained Application

After debugging and testing the application, create the files to be deployed.

Publish from Visual Studio

Right click on Project name (not the solution) in Visual Studio Solution Explorer and select Publish.

In the main area on ensuing screen, select Start below Publish.

Select Folder in the ensuing Pick a Publish Target dialog box

Create the profile by selecting the drop-down list icon next to the Publish button and selecting Create Profile.

06

In Publish screen, select Configure link

In Publish Dialog box, under Connection section ensure you have File System selected as Publish Method and select Next

Under Settings section, ensure you have Self Contained selected as Deployment Mode and linux-x64 as Target Runtime and select Save

07

Back in Publish Screen, select Actions Drop Down and select Rename Profile. Provide a name in the ensuing dialog box to name your profile for later reuse.

Finally in Publish Screen, select Publish button to publish your application.

08

Publish from Command Prompt

On development machine (in our case, our Windows machine), open a command prompt at the root of your web application (location where .csproj file exists) and run the following.

dotnet publish -c release -r linux-x64

Note: Each target location (binreleasenetcoreapp2.1publish) contains the complete set of files (both app files and all .NET Core files) needed to launch app. Also, the startup application generated for our project is the name of the project without an extension.

Create a Simple Application Server Instance on Alibaba Cloud

Log in and Select Simple Application Server

If you do not have Alibaba Cloud Account get one free at https://account.alibabacloud.com/register/intl_register.htm

Log in and select Simple Application Server under Products

9

Click on buy now/ Create Server to start the process of configuration setup

Setup Server Configuration

Region

Select the region nearest to your customers / prospective customers.

Image

Select the OS Image option under Image and select CentOS as shown in image.

10

Instance Plan

Select the necessary hardware configuration.

Subscription

Select the necessary period for the server.

Current Selected

Verify the options you selected in previous steps.

Click on Buy Now.

Pay

Confirm order and select Pay using your credit card or coupon if available.

Pay for your order.

You should now receive the payment complete page as shown in below image.

11

Deploy application on simple application server

Create Password

Log back into console and select Simple Application Server

You should see the CENTOS Server running.

Click on right top of server info and select details as shown in below image.

12

Now you should be able to see the Server Management Screen.

Select Connect under Server Maintainance.

Please note the server IP Address. You will need it very shortly.

Select Set Password.

13

Provide a password to the root account for your server.

If you do not have putty Installed get it from https://www.putty.org/ and install on your local machine.

You need the above software to access server terminal.

Open putty.

14

Add the server IP Address you noted earlier and choose Open.

A terminal window opens and shows login as:

Add root and press enter
Add password you set earlier for server
You are now ready to add commands to the terminal

Install Prerequisites on Server

yum

yum is the primary tool for getting, installing, deleting, querying, and managing software packages in CentOS. First we use it to update software repository to the latest versions.

sudo yum -y update

Nginx

Nginx is a web server which can act as a reverse proxy. A reverse proxy server can offload work such as serving static content, caching requests, compressing requests, and SSL termination from the HTTP server.

sudo yum install nginx

When it asks if this is OK[y/d/N]: y

Start the Nginx service using the below command

sudo service nginx start

Check to ensure Nginx was setup properly.

systemctl status nginx

Now, hitting Nginx from the public IP assigned to your server should show the welcome screen as shown in image below.

15

nano

GNU nano is a small and friendly text editor useful for editing configuration files.

sudo yum update
sudo yum install nano

When it asks if this is OK[y/d/N]: y

Supervisor

Supervisor is a client/server system that allows its users to monitor and control a number of processes on UNIX-like operating systems.

sudo yum update
sudo yum install supervisor

When it asks if this is OK[y/d/N]: y

Deploy Application

There are multiple ways of moving published application files to the server including the usage of FTP Client. We will use Filezilla. To install Filezilla for free visit https://filezilla-project.org/

In Filezilla, Select File > SiteManager

Select sFTP as Protocol

Add server ip address as Host, 22 as Port and Normal as Logon Type

Add root as User, Password as the one you set earlier and select Connect

16

Once logged in, create a directory (we named dotnetappdir) and drag and drop publish folder in the same.

As we have configured our .Net Core application to run on port 5000, we now need to Configure firewall such that requests to port 5000 are allowed.

Go back to the Server management screen on AlibabaCloud Console and select the option Firewall under Security.

Click on button Add Rules and add a firewall rule as shown in image below.

17

Now back at putty bash screen, move inside the folder where the published files are uploaded (in our case dotnetappdir/publish)

Grant execution privileges on the application, by executing the following command:

chmod +x alibabadotnetcore

Run our application now with the following command:

./alibabadotnetcore

Now, you should see output to show the application is running properly. If you check on browser with server_ip_address:port_number (port number=5000), you should see the application running as shown in image below.

18

Shut down the application by pressing Ctrl +C

Configure Nginx

Now, we configure NGINX to serve our .NET Core web application as a reverse proxy.

At putty bash screen, backup the existing Nginx configuration file

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Edit the Nginx configuration file

sudo nano /etc/nginx/nginx.conf

The nano editor opens. Check for the Server > Location Configuration area.

If you can not see the Server or Location, do a ctrl + v to view next page block.

Once you see location, take the cursor inside the location block and copy the below text and paste the same by right clicking (if does not work try shift + right click).

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;
    }

Save your changes by hitting ctrl+x, then Y and finally enter.

19

Ensure your Nginx configuration changes checkout as valid syntax.

sudo nginx –t

Reload Nginx

sudo nginx -s reload

Change directory to folder where dotnet application files reside.

cd dotnetappdir/publish

Run the dotnet application

./alibabadotnetcore

Now, check on browser with server_ip_address, you should see the application running as shown in image below.

20

Final Steps

Close the terminal and now refresh the browser window.

The nginx error page shows :

nginx error!
The page you are looking for is temporarily unavailable. Please try again later.

This shows that the Terminal close also shuts the ASP.NET application.

So, we need a method which will keep the ASP.NET application running even after Terminal close. We use Supervisor to do the same.

First lets copy our application files from home folder to /var folder

cp -r ~/dotnetappdir /var

Now, we create a startup script and edit the same

touch /var/dotnetappdir/startscript
nano /var/dotnetappdir/startscript

And add the following lines which basically tell how to start the dotnet application

#!/bin/sh
cd /var/dotnetappdir/publish
./alibabadotnetcore

Save and Make the startup script executable

chmod +x /var/dotnetappdir/startscript

Now we edit the supervisor configuration file

nano /etc/supervisord.conf

And add at the end of the file the following lines

[program:start_script_alibabadotnetcore]
command=/var/dotnetappdir/startscript
autostart=true
autorestart=true
stderr_logfile=/var/dotnetappdir/alibabadotnetcore.err.log
stdout_logfile=/var/dotnetappdir/alibabadotnetcore.out.log

Save and run supervisor by following command

sudo supervisord -c /etc/supervisord.conf

Now, check on browser with server_ip_address, you should see the application running.

Close the terminal and then refresh the browser, you should still see the application running.

Conclusion

These are the basic steps one has to do to deploy an ASP.NET Core application after building the same on Visual Studio on Alibaba Cloud Simple Application Server with CentOS.

0 0 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments