How to deploy Asp.net Core app to Linux Droplet

Steps;

Connect to server

ssh root@<Your Server IP>

.Net sdk install on server,

wget https://packages.microsoft.com/config/ubuntu/18.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 apt-transport-https
sudo apt-get update
sudo apt-get install -y dotnet-sdk-3.1

Let’s create the path;

sudo mkdir /var/www/
sudo mkdir /var/www/
sudo chown -R dries:www-data /var/www/

Let’s clone our project here

git clone <your repo git address.git>

Build and publish project

dotnet build
dotnet publish

Install nginx

sudo nano /etc/apt/sources.list

deb http://nginx.org/packages/ubuntu/ xenial nginx
deb-src http://nginx.org/packages/ubuntu/ xenial nginx

sudo apt-get update
sudo apt-get install nginx

sudo service nginx start

Welcome Nginx message when enter url with Your server ip

Add an SSL certificate with Certbot

sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot python-certbot-nginx
sudo certbot --nginx

Forward requests to our app

sudo nano /etc/nginx/sites-available/sites.com
server {
    listen        80;
    server_name   ;
    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;
    }
}

linked,

sudo ln -sf /etc/nginx/sites-available/sites.com /etc/nginx/sites-enabled/
sudo nano /etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
http{
    ...
    include /etc/nginx/sites-available/sites.com;
}
sudo service nginx restart

Create service

sudo nano /etc/systemd/system/dotnet-project-name.service
[Unit]
Description=My application service

[Service]
WorkingDirectory=/var/www/
ExecStart=/usr/bin/dotnet /var/www//.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

In my case,

[Unit]
Description=My application service

[Service]
WorkingDirectory=/var/www/oguzhanabali-dev-demo-web
ExecStart=/usr/bin/dotnet /var/www/driesdeboosere-dev-demo-web/Oguzhanabali.Dev.Demo.Web.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=oguzhanabali-dev-demo-web
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

Permission access to folders,

 

sudo chown -R root:root /var/www/
sudo setfacl -R -d -m u:root:rwx,g:root:rwx,o::r /var/www/
sudo service oguzhanabali-dev-demo-web start
sudo systemctl | grep oguzhanabali-dev-demo-web

That’s it! Now your web server will keep running your ASP.NET Core app, even if you exit the server.

Asp.net core https redirect ERR_TOO_MANY_REDIRECTS (on IIS)

Hi,

Your project after you deploy on IIS; when you want to do http to https redirect;
“ERR_TOO_MANY_REDIRECTS” brush up against.

For Solution add in startup.cs;

public void ConfigureServices(IServiceCollection services)
{
  services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
            });
  services.AddHttpsRedirection(opts => {
                opts.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
                opts.HttpsPort = 443;
            });
}

and,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
..
 app.UseHttpsRedirection();
..
}

Asp.Net Core Deploying ERR_TOO_MANY_REDIRECTS ERROR ON IIS

Hi everyone,

You made a asp.net core. Everyting is okey in local. But on IIS deploying there is a problem.

Solution:

 <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />

to

 <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />

Asp.Net Core and Cookies

Enable Cookies in Project for:

Startup.cs file in insert

And this using cookies for:
 string username = Request.Cookies["username"];
 string password = Request.Cookies["password"];

 

Asp.Net Core Session Not Working (Solution)

Startup.cs file in;

services.Configure<CookiePolicyOptions>(options =>
            {              
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

change to:
options.CheckConsentNeeded = context => false;

Kestrel Server Different Port with Run For Asp.Net Core (Nginx)

Create kestrel service:

nano /etc/systemd/system/kestrel-oguzhanabali.com.service
[Unit]
Description=Oguzhan ABALI Blog

[Service]
WorkingDirectory=/var/www/oguzhanabali.com
ExecStart=/usr/bin/dotnet /var/www/oguzhanabali.com/OguzhanAbali.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

Add the code below:

Environment=ASPNETCORE_URLS=http://localhost:5001

Asp.Net Core appsettings json get value in static class

Example appsettings:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Create MyConfig name class and;

using Microsoft.Extensions.Configuration;
static class ConfigurationManager
{
    public static IConfiguration AppSetting { get; }
    static ConfigurationManager()
    {
        AppSetting = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    }
}

Now you can use it like :

string value = ConfigurationManager.AppSetting["value_Key"];

Asp.net MVC Css Menu Active Class

Selamlar,

Solutionunuzda “Helpers” adında bir folder oluşturduktan sonra HtmlHepers.cs adında bir class oluşturuyorsunuz ve bu class aşağıdaki kodlardan oluşuyor.

public static class HtmlHelpers

{

public static string ActivePage(this HtmlHelper helper, string controller, string action)

{

string classValue = "";

string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();

string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

if (currentController == controller && currentAction == action)

{

classValue = "active";

}

return classValue;

}

}

 

Sonrasında _layout türevi menüyü yazdığınız yerde class=”@Html.ActivePage(“Home”,”Index”)” ekliyorsunuz. Bu size active stringini döndürecek. classValue=”active” bunu eğer active classınız farklıysa değiştirebilirsiniz.

İyi çalışmalar herkese..