VisualStudioCode創建的asp.net core項目部署到linux,使用nginx代理

1、準備工作:

  a:使用VisualStudioCode創建asp.net core項目,併發布(可以參考前面兩篇文章)。

  b:把發佈的 asp.net core項目上傳到linux服務器上(我的linux的代碼路徑爲“/var/wwwroot/netcoretest”)。

  c:linux服務器上安裝.net core sdk。

 

2、asp.net core代碼注意地方:

  由於請求是通過nginx反向代理轉接的,因此使用 Microsoft.AspNetCore.HttpOverrides 包中的轉接頭中間件。

  此中間件使用 X-Forwarded-Proto 標頭來更新 Request.Scheme,使重定向 URI 和其他安全策略能夠正常工作。

  所以在項目的Startup.cs中做如下修改:

  

  

3、配置nginx:

複製代碼

server {
    listen        8003;
    server_name   example.com *.example.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;
    }
}

複製代碼

 

4、在linux服務器上運行項目:

切換到項目代碼目錄下(我的linux的代碼路徑爲“/var/wwwroot/netcoretest”),使用命令“dotnet admin.dll”(admin爲我的項目名)運行項目,如下圖:

上面的warn可以忽略。

.net core項目默認監聽端口爲5000,代碼中可以在launchSettings.json中修改。

這時,在瀏覽器中輸入地址http://XXXXX:8003 就可以了,如下圖(下面是創建.net core mvc 默認站點界面):

 

5、也可以建一個自定義服務,用於維護.net core項目進程,使項目的開機自動啓動:

 a、新建自定義服務:vim /etc/systemd/system/mydotnetcore.service

 b、服務代碼內容如下:

複製代碼

[Unit]
Description=dotnet core demo running on linux

[Service]
WorkingDirectory=/var/wwwroot/netcoretest
ExecStart=/usr/bin/dotnet /var/wwwroot/netcoretest/admin.dll
Restart=always
RestartSec= 10
SyslogIdentifier=dotnet core demo
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production 

[Install]
WantedBy=multi-user.target

複製代碼

c、啓動服務

systemctl start mydotnetcore.service

即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章